Repository navigation
Windows installer: emit the native path helper instead of compiling it - #10540
Conversation
Bitdefender blocks Unsloth Desktop during the first "Get started" run on Windows 11, including elevated. The chain it reports is unsloth-stud... -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll and the verdict lands on the generated DLL (Gen:Variant.MSILHeracles), not on anything we ship. Bisecting the reports: 0.1.800-beta installs fine, 0.1.803-beta and later block. In that window the installer went from one Add-Type compile to two, the second retrying under a private TEMP after the first failed. Every shipped exe in the range is 0/70 on VirusTotal, so the shipped bytes are not what is being detected; the behaviour is. Add-Type -TypeDefinition on Windows PowerShell 5.1 has no in-process compiler, so it writes C# to %TEMP% and shells out to csc.exe to produce a DLL it then loads. PowerShell launching a compiler that emits executable code into %TEMP% is a generic malware pattern, and heuristics fire on it. The only thing the installer needed from that compile was three kernel32 P/Invoke declarations used to resolve a final path across a reparse point. Reflection.Emit builds exactly those, in memory: DefineDynamicAssembly with AssemblyBuilderAccess::Run, then DefinePInvokeMethod per import. No compiler process, no source file, no DLL on disk, and the assembly reports an empty Location. Available on .NET Framework 4 and on .NET 5+, so 5.1 and 7 take the same path. Changes: - Initialize-StudioFinalPathNativeType emits CreateFileW, GetFinalPathNameByHandleW and CloseHandle via DefinePInvokeMethod. - Drop the private-TEMP retry added for the earlier compile failure. There is no compiler to fail, and that retry is the second csc.exe launch in the chain above. - Get-StudioNativeFinalPath is now non-throwing end to end. DefinePInvoke cannot request SetLastError, so Marshal.GetLastWin32Error is not meaningful here; a failed call returns null and the caller drops to the existing lexical answer with -Exact false, exactly as before. - Get-StudioProcessImagePath loses its native branch. OpenProcess and QueryFullProcessImageNameW existed only to shortcut what Get-Process and Win32_Process already answer, and both were already the fallback. install.ps1 now contains zero Add-Type -TypeDefinition sites. Tests: - tests/studio/test_native_path_resolver_degrades.ps1 runs the real extracted resolver under pwsh on POSIX, where kernel32 does not resolve, which is the same state as a host whose helper was taken away. It asserts the type defines, nothing is written to the temporary directory, the assembly is memory-only, and a native call that cannot work returns null rather than throwing. - test_installer_av_shapes.py learns to read imports declared through DefinePInvokeMethod, asserts no C# compiler is invoked, and keeps asserting the lexical fallback is still reachable. Behaviour is unchanged on a machine where the native call works: same exact path, same -Exact true. On a machine where it does not, the caller already handled null and fails closed on the runtime lock as before.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…e integrity gate Review of the first commit turned up three things. 1. install.ps1 still compiled C# twice. Add-Type -MemberDefinition reaches csc.exe exactly as -TypeDefinition does: it wraps its argument in a class and compiles that. Two sites were left, the virtual-terminal console thunk and the Explorer icon refresh, and the argument for leaving them was conditional: the redirect guard keeps the desktop app off the first, and Tauri returns before the second. A guard that holds only for the entrypoint we happened to look at is what let this reach the field in the first place, and the standalone `irm | iex` path reached the console compile on every run. Both now emit. The three emit sites share one helper, New-StudioEmittedNativeType, and studio/setup.ps1 carries its own copy for its own console thunk, which was compiling too. Add-Type no longer appears in either script. -AssemblyName would be the one acceptable form, since it loads an assembly that already exists and reaches no compiler, but neither script uses it outside a generated launcher. 2. Dropping the native process-image rung was a regression. The first commit removed OpenProcess and QueryFullProcessImageNameW from Get-StudioProcessImagePath on the grounds that Get-Process and Win32_Process already answer. They do not always. Process.Path goes through MainModule, which needs PROCESS_VM_READ and is refused across users and across bitness, while QueryFullProcessImageNameW needs only PROCESS_QUERY_LIMITED_INFORMATION and Win32_Process needs a working WMI service. With neither answering, Get-RunningStudioVenvProcesses finds nothing and the install proceeds over a venv Unsloth still has open, which is the case its abort exists for. The rung is back, emitted rather than compiled. The ladder is now identical to the one on main. 3. Reflection emit has one failure mode that cannot be caught. App Control's Dynamic Code Security (policy option 19) always blocks loading unsigned assemblies built with System.Reflection.Emit, and Microsoft documents the parent process as usually stopped or crashing rather than raising, so a try/catch around the emit is not enough: learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/design/appcontrol-and-dotnet Test-StudioCanDefineNativeTypes is now the gate every emit site checks first. It keeps the Constrained Language check, which is what fires in practice since a host enforcing user-mode code integrity puts PowerShell in Constrained Language, and adds a Win32_DeviceGuard probe for a policy that somehow left the language mode alone. Unreadable means unrestricted: a host with no Device Guard at all is the common case and is not a reason to refuse. Also: stale comments describing the compile, the CS2001 failure and the private TEMP retry, none of which exist any more. Tests: - tests/studio/test_native_path_resolver_degrades.ps1 now parses install.ps1 with the PowerShell parser rather than the brace-counting extractor in tests/studio_setup_ps1, which runs past the end of any function holding a brace inside a string; Resolve-StudioLinkTarget has one. It runs the whole ladder, not only its top rung, and asserts the lexical answer still arrives with Exact false, that both process-image rungs answer, that GetConsoleMode's out parameter is emitted by-ref and SHChangeNotify still returns void, and that defining a type twice neither throws nor corrupts the first definition. - test_installer_av_shapes.py bans Add-Type in both scripts rather than -TypeDefinition in one, and OpenProcess and QueryFullProcessImageNameW are back in the allowed import inventory with the reason they cannot be replaced. tests/studio plus the Windows installer guards: 8688 passed, 215 skipped. The real install, setup, update and repair entrypoints under tests/studio/test_path_probe_access_denied.ps1: all checks passed.
Staging CI caught a whole test file I never ran: tests/python/test_windows_installer_addtype_fallback.py, 1612 lines built entirely around the compile-and-retry path this branch removes. Five of its tests failed. My local runs covered tests/studio, the Windows concurrency guard and a handful of tests/test_installer_*, and none of them reach this file. Two of the five were collateral. LOCK_CHAIN extracts the resolver chain function by function, and the chain gained Test-StudioCanDefineNativeTypes, New-StudioEmittedNativeType and Get-StudioNativeFinalPath, so the link-resolution tests were calling helpers the harness never defined and reading the CommandNotFound as "could not resolve". The other three described the removed design and had to say something else: - test_install_lock_is_acquired_when_the_compiler_fails is now test_install_lock_is_acquired_when_the_native_helper_is_unavailable. The bug in #9140 was a throwing Add-Type; the same bug now is a host that cannot define a type at all, which is the same thing to every caller, and NO_NATIVE overrides the gate both Constrained Language Mode and Dynamic Code Security come through. - test_the_compiler_is_not_retried_for_every_path asserted CALLS:2, one attempt plus one private-TEMP retry. It is now test_the_compiler_is_never_called_however_many_paths_are_resolved and asserts zero. The caching that count stood in for gets its own test against the emit. - test_the_private_temp_retry_recovers_the_native_helper becomes test_the_native_helper_is_built_with_no_usable_temp_at_all. The retry existed because compiling wrote a source file into %TEMP%; emit writes nothing anywhere, so the same unusable %TEMP% is simply irrelevant, and the assertions that TMP and TEMP are handed back untouched carry over unchanged. New: test_a_dead_compiler_is_not_something_the_installer_can_notice. Sabotaging Add-Type has to change nothing at all now, which is the property worth pinning, and a failure there means a compile came back. Renamed to test_windows_installer_native_type_fallback.py, since the fallback it guards is no longer about Add-Type. Nothing references the old name. The file: 58 passed. Also checked, and NOT mine. Five other failures in that staging run reproduce on a clean worktree of origin/main at b75ed88: tests/test_windows_amd_gpu_scan_fallback.py 4 failures tests/test_deliberate_crashes_suppress_cores.py 1 failure test_installer_restores_the_private_handoff_after_setup asserts $previousRocmGfxHandoff appears after the --with-llama-cpp-dir error, and on main it appears before it. PR 10494's branch passes it because it predates whichever commit reordered them. Left alone here rather than fixed in a branch about something else. Same for the two tests/python failures outside this file (test_e2e_no_torch_sandbox, test_rl_config_pickling): both fail on origin/main and neither reads install.ps1. The Clean machine install leg fails on linux ubuntu2404-arm-root with "built from source: nvidia-npp-cu13", an aarch64 wheel that does not exist. A Windows PowerShell change cannot reach it. Wider run on this branch: tests/python 2322 passed, 129 skipped, 2 pre-existing failures; tests root filtered to installer and Windows, 1503 passed, 35 skipped, 4 pre-existing failures.
…ess tree The degraded warning said "Continuing with the PowerShell resolver; installation is unaffected." That is a promise this line cannot keep. Every condition that stops a type being defined here is security software or a lockdown policy acting on the process, and the same thing can be acting on the rest of the run; saying the install is fine is exactly the reassurance a user then finds was wrong. It also said nothing useful. The narrower claim is both true and actionable: the installer continues, and the answer it continues with is inexact in a specific way, so a path is compared as written rather than as stored.
The text guard in test_installer_av_shapes catches an Add-Type that is written
in one of these scripts. It cannot see a compile reached through a module, a
dot-sourced file or a generated here-string, and it cannot see one a dependency
performs while our own process tree is what a scanner scores. Bitdefender scored
the chain, not the bytes:
unsloth-studio.exe -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll
so there has to be a lane that runs the installer and asserts on processes.
Two independent detectors, since either alone can be defeated by something that
is not the code under test. Security event 4688 is authoritative about what ran
and sees a compiler spawned at any depth. A sweep of every temporary directory
for new .dll, .cmdline and .rsp files survives auditing being silently overridden
by a machine policy, and catches an assembly that was written and cleaned up.
The positive control runs first and is not optional. A detector that sees nothing
reads exactly like a clean run, and every part of this can fail to apply without
saying so. The job compiles one throwaway type with Add-Type and requires both
signals to fire; if either does not, it fails as a broken detector rather than
going on to report a meaningless pass.
The installer is spawned as a child powershell.exe rather than dot-sourced,
because the shape under test includes what the installer's own children do.
What this cannot answer: a hosted runner has neither App Control nor Smart App
Control enforcing, so a green run says the install path spawns no compiler and
drops no temporary DLL. It says nothing about what an enforcing machine would do.
Also corrects a stale comment: setup.ps1 emits its console thunk now too, so
neither script compiles anything.
…est in CI Review raised that Windows PowerShell 5.1 on .NET Framework does not expose the static AssemblyBuilder::DefineDynamicAssembly, and that the emit would therefore throw into the catch, cache the resolver as unavailable, and leave every desktop install on the lexical fallback, which can give a long path and its 8.3 alias different install mutex names. The premise looks wrong: the API reference lists netframework-4.5 through netframework-4.8.1 in the applies-to range for both overloads, alongside the .NET Core monikers, with mscorlib.dll among the assemblies. But nothing in this repository can run a .NET Framework host, the claimed failure is silent rather than loud, and the cost of covering both is four lines, so New-StudioDynamicAssembly tries the static and falls back to AppDomain.CurrentDomain.DefineDynamicAssembly. Order matters and is not arbitrary. Measured on pwsh here: the static returns a RuntimeAssemblyBuilder with an empty Location, and the AppDomain spelling is absent and throws RuntimeException. So the AppDomain call cannot be the first try without breaking the host we can actually test, and it is the fallback instead. Registering tests/studio/test_native_path_resolver_degrades.ps1 with the CI step was also raised, and it earned its place immediately: adding the helper broke 18 of its checks, because it loads the resolver's functions by name and the new one was not in the list. That is exactly the regression it exists to catch, and until now nothing ran it. It is now in the PowerShell installer unit tests step beside the others, and two source checks assert that neither spelling can be dropped.
…t the new helper Seven items, all correct, three of them bugs in code added yesterday. Each was reproduced before it was fixed. The watcher returned the wrong thing. `& $Action` leaves the action's success stream on the function's output, and the installer action tees its log, so every line was emitted ahead of the result hashtable: the caller's $seen became an Object[] of length 2 and $seen.Compilers failed under Set-StrictMode against a string rather than reporting the measurement. Piped to Out-Host now. The watcher also died on a clean machine. Get-StudioTempArtifacts returned an empty array, PowerShell unrolled it to nothing on return, and the two-argument HashSet constructor rejects null, so Invoke-WithCompilerWatch threw a MethodInvocationException before running even the positive control. Both reproduced in miniature on pwsh; both now return a Hashtable with the action still logging. The 4688 query had no end time, so a compiler started by anything else while the recursive temp sweep was still running counted against an action that had already finished. The window closes before the sweep now. The prose claimed a process tree, which the implementation never did: 4688 carries the creator's pid, but a compile can be several processes deep and those pids have exited by the time the log is read, so the ancestry is not reconstructable after the fact. The docstring says that instead of implying otherwise. The job measured only the shell mode. install.rs initialises its argument list with --tauri unconditionally, so a compile reached through a Tauri-only branch was invisible to a job triggered by changes to that launcher. Both modes run now; the desktop leg unpins UNSLOTH_STUDIO_HOME rather than changing the mode, since the desktop mode refuses it, and it is not gated on exit 0 because the question there is only whether a compiler ran. The path filter omitted the watcher, which implements both detectors, so a PR touching only it could disable the detection without running the control. New-StudioDynamicAssembly was missing from the concurrency guard's three extraction lists, and that test caught it exactly as designed: "_mutex_helpers extracts functions that call ['New-StudioDynamicAssembly'], which the harness never defines". Two tests were failing and I had not run that file. The resolver test counted every matching temp file touched in the last minute as this emission's output. Demonstrated: one unrelated .dll dropped in the shared temp directory makes the old rule report TEMP_ARTIFACTS: 1 and fail a run that wrote nothing. It is a set difference against a snapshot taken before initialization now, which is what the assertion actually means.
The compiler check itself was broken, which is the worst of the three: it failed on every healthy runner and would have failed on a machine that really did spawn csc.exe for the same reason, so it graded nothing. auditpol returns an ARRAY of lines, and -notmatch on an array is a filter, not a test: it returns the elements that do not match. On a runner where auditing turned on correctly it still returned the three header lines, and a non-empty array is truthy, so the guard threw with "process creation auditing did not turn on" directly under output reading "Process Creation Success". Joined to one string and matched on the subcategory line. Checked against the two other match operators in the PR; both operate on single strings and are fine. tests/studio/test_installer_av_shapes.py reads a workflow file, and the repo requires any such guard to run in workflow-trigger-lint, the one job with no paths filter, so a PR that edits only workflows still runs it. Added there. The VT parity test sliced Enable-StudioVirtualTerminal without the helpers it calls. Extracting the emitted-type path gave that function two new callees, so the reconstruction representing the predecessor died with an unrecognised command and exited 1. That reads as "the predecessor disagreed" when in truth it never ran. The slice now carries Test-StudioCanDefineNativeTypes, New-StudioDynamicAssembly and New-StudioEmittedNativeType, and both reconstructions parse clean with no unresolved commands. The assertion also printed only the passing run's stderr, so the reconstruction's own error was never shown and the failure was undiagnosable from the CI log. It prints both sides now.
…caught Only reachable on a real Windows or macOS runner, so none of them had run before. test_versioned_native_helper_loads_after_older_installer_type asserted on UnslothStudioFinalPathV2 and called GetProcessImagePath on it. The type is UnslothStudioFinalPathV3 and that method belongs to UnslothStudioProcessImageV1, so under ErrorActionPreference Stop the script threw and the test reported a bare exit status 1. It now checks that the versioned type is defined and that the resolver returns a real path even though an older installer already put UnslothStudioFinalPath in the session. _run_powershell no longer passes check = True. The PowerShell error was being discarded, which is what made the failure above unreadable; the output is now attached to the assertion. test_the_sweep_only_takes_directories_the_allocator_could_have_made created ust-<pid>-abcdef01 and ust-<pid>-ABCDEF01. NTFS and the default macOS filesystem are case-insensitive, so the second mkdir raised FileExistsError before the sweep ran. The uppercase directory now uses a second dead PID. test_unequal_paths_are_unknown_rather_than_different_when_inexact reached the inexact path by making Add-Type throw. The installer no longer calls Add-Type, so on Windows the emit succeeded, the answer was exact, and two directories compared false. It now goes through the capability gate.
Microsoft documents that App Control option 19, Dynamic Code Security, always blocks loading unsigned assemblies built with System.Reflection.Emit, that there is no audit mode for it on Windows 10 or on Windows 11 before 24H2 (it is turned on and enforced there even when the policy is in audit mode), and that a blocked dynamic load usually stops or crashes the parent process. The gate only refused enforcement status 2, so a machine running an audit-mode policy with that option would have reached the emit. Win32_DeviceGuard does not report the option bit, and no catch recovers a stopped process, so any active user-mode policy now takes the lexical path instead. That degradation is one the installer has always had and completes on; a crashed installer is not. Also from the same audit: - The open now sits inside the region that closes it, in both native helpers. A SafeFileHandle had a finalizer as a backstop between the open and the using block and an IntPtr has none. The handle is opened with desired access 0 and full sharing, so a leaked one blocks nothing, but the window did not need to exist. The close is guarded, since the failure paths now reach the finally. - CreateType can publish a type and then throw on the way back. The compiled version checked for that before giving up and the replacement did not, which turned a recoverable failure into lexical resolution for the rest of the run. - CharSet is declared per import rather than Unicode for all of them. It selects which export the runtime probes first, and CloseHandle, OpenProcess and the three console calls were CharSet.None in the C# this replaces. Every name here exists exactly as written so both orders resolved, but the metadata now says what the declaration said. Tests cover the gate on both scripts at status 0, 1 and 2 and with no provider at all, the charset carried by each emitted import, and the published-then-threw path.
…he stub real Two defects the cross-OS audit found, neither of which any lane could have reported. tests/studio/test_native_path_resolver_degrades.ps1 ran only on a windows-latest job. Its premise is a host where the emit succeeds and kernel32 does not resolve: it asserts the native rung answers null and the ladder reports the result inexact. On a healthy Windows runner those calls succeed and those assertions are false. It moves to the Linux leg of cross-platform-parity-ci.yml, and the file now exits early on Windows with the reason rather than failing a dozen checks that describe a different machine. The throwing-resolver test still defined UnslothStudioFinalPathV2, which nothing calls now, so the resolver fell back because the type was ABSENT and the test passed without ever reaching the stub. It defines V3, which is what the resolver calls, and counts its invocations: the assertion is now that the throwing path ran four times, not merely that the outcome looked the same.
|
Five independent audits of this change plus #10560, each asked a different question, and a cross-OS run on six runners plus WSL and MLX. Four of the five found something; three of those were real and are fixed here. Fixed: the capability gate let an audit-mode policy through. The gate refused only enforcement status 2. Microsoft documents that App Control option 19, Dynamic Code Security, always blocks loading unsigned assemblies built with Fixed: the throwing-resolver test never reached its stub. It defined Fixed: Fixed, from the same audits, smaller:
Recorded, not changed:
Member by member, the emitted and compiled declarations agree on library, entry point name, calling convention ( Cross-OS run, all green: windows-x64, windows-arm64, ubuntu-x64, ubuntu-arm64, macos-arm64, macos-intel, Ubuntu under WSL on a Windows host, and the macOS MLX branch. The Windows legs are the ones under test; the rest are the control for "a change confined to Windows disturbed nobody else". That run is also what caught three Windows-only test defects that had never executed anywhere: a test asserting |
…lose the watcher window after the baseline Two review items, both correct. The desktop-mode leg accepted any exit code, which is right: a --tauri install can decline for reasons that have nothing to do with whether a compiler ran. It also accepted a run that stopped at argument validation, which spawns nothing, so both detectors came back empty and the step printed "no compiler" having measured nothing. It now requires the log to show the run reached install work, and calls the result void rather than clean when it did not. Watch-ForCompiler recorded $since before the baseline temp sweep. That sweep walks every temp root recursively and can take seconds, so an unrelated csc.exe started during it landed inside the window and failed either the positive control or the installer measurement for something neither did. The baseline is taken first and the window opens after it, which is the same ordering the closing side already used.
…ould not (#10624) Follow-up to #10540. Two of the tests it added only pass on POSIX, and nothing in CI noticed because the Windows row of cross-platform-parity-ci.yml does not run that file. On a real windows-latest runner twelve cases fail. The retry test stubs the child probe but not the Device Guard query. On Linux that query fails and the gate falls through to the probe; on Windows it succeeds with status 0 and the gate returns before the stub is ever called. It now stubs the query too, the way the active-policy tests next to it already do, so the case under test is reached on either host. The acceptance and deadline tests hand a shell script to Process.Start as a stand-in host. Windows cannot execute a file with no executable format, so every case comes back false through the catch: the accept case fails outright and the deadline case passes without ever waiting, which is worse. Both are marked POSIX only with that reason, since what they measure is host-independent PowerShell logic. Then the file joins the Windows parity row, so the next test that only works on one platform is caught by CI rather than by hand.
* Windows installer: shorten the native-type comments Comment-only follow-up to #10540. The notes around the reflection-emit helpers, the emit gate, the compiler watcher and its CI lane restated the same point twice and narrated history at length. Tightened them to the minimum that still explains why the code is the way it is: every API name, exit code, policy option, timeout and reproduced observation is kept, only the restatement is gone. No code, string literal or test data changed. * Rewrap one comment to the file's own width * Say where strict mode actually comes from in each script --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: oobabooga <[email protected]>
tests/sh/test_tauri_retry_failure_context.sh asserts studio/setup.ps1 exits in exactly one place, the tail of Exit-SetupFailure. It counted `exit` lines with a grep over the raw file, so when #10540 made the installer emit its native path helper through a here-string instead of compiling it, the emitted probe's `exit 1` counted as the installer's own and main went red. The installer change is right; the test was reading the wrong text. tests/sh/_ps1_source.sh adds ps1_code, which blanks here-string bodies and keeps one blank line per body line so grep -n and sed addresses still point at the real file. Two details it has to get right, both learned from the files themselves: the opener is detected with quoted strings blanked first, because setup.ps1:909 and install.ps1:2280 redact credentials with a -replace whose line genuinely ends in @'; and the terminator must sit in column 0, because install.ps1 builds a .bat from an array containing "@echo off",. Two more readers were looking at emitted text: - tests/studio/test_installer_av_shapes.py opened a here-string on that same redaction line, then stayed open until the next terminator. Every check in the file silently skipped setup.ps1:910-1692 and install.ps1:2281-3024. With the fix those lines are scanned again and all 44 assertions still hold. - tests/sh/test_install_rollback_lifecycle.sh matched `} finally {` inside the emitted launcher at install.ps1:2894, and passed only because grep -A3 concatenated the context of all four matches. tests/sh/test_ps1_code_view.sh guards the filter both ways: an exit added to real code is counted, an exit added inside a here-string is not.
…scarding the packets Every report of security software blocking Unsloth (#8523, #6326, #6588, #6648, #10540, #10805) named no antivirus product, no detection name and no AMSI provider. Clearance is per hash and vendors act on a detection name, so not one of those reports could be submitted anywhere, and not one of the six hardening passes since can be shown to have fixed what it aimed at. That is the gap here. ## A required-field issue form `.github/ISSUE_TEMPLATE/install-blocked-windows.yml`, a form rather than a markdown template for one reason: a form can mark a field `required` and a template cannot. Required: the product and version, the detection name exactly as displayed, the full error including the `FullyQualifiedErrorId` line, and the output of a collection script. Also a dropdown separating "the script would not run at all" from "something it created was blocked", because those are different mechanisms with different fixes and have been conflated in past reports. The script reads registered antivirus products from `root/SecurityCenter2`, resolves each AMSI provider CLSID through `InprocServer32` to a DLL and reads its `CompanyName`/`ProductName`/version, then `Get-MpComputerStatus` and recent Defender events. The provider resolution is the part that actually answers "which product", since a bare CLSID is not actionable. So is `AMRunningMode`: anything other than `Normal` means another product is primary. It downloads nothing, writes nothing, and changes nothing -- and it deliberately carries none of the shapes the installers are being cleaned of, because a diagnostic that trips the same product that blocked the installer is worthless. A test enforces that: no `Add-Type`, no `Invoke-Expression`, no base64, no `Set-MpPreference`, no `Remove-Item`, no `Start-Process`. ## The packets that were being thrown away Two false-positive submission packets are built today and discarded. `release-desktop.yml` writes a Microsoft submission packet to `$RUNNER_TEMP` and never uploads it, so `flagged-windows-bundles-*` held the flagged bundles and nothing describing them; it is now included in that artifact. And `scripts/virustotal_scan.py`'s packet went only into a job summary, which is ephemeral, so the one document written for the purpose of disputing a detection was discarded along with the run; it is now kept as an artifact. Retention on the flagged bundles goes from 7 days to 90. Clearance is per hash and a rebuild hashes differently, so those copies are the only submittable sample for that release, and a vendor round trip plus our own reaction routinely outlasts a week -- after which the evidence for the detection being disputed is gone. `test_the_scan_job_is_not_conditioned_away` allowed `if: always()` on exactly one step. The new upload needs it for the identical stated reason, "precisely so the evidence survives a failed scan", so the exception becomes a named set of two rather than a shape a future step could inherit by resembling. ## Verification - 675 passed, 6 skipped across `tests/security/` and `tests/python/test_virustotal_scan.py`. - The collection script is extracted from the YAML and **parsed**, not eyeballed. It is pasted verbatim by people who are already stuck, so a syntax error in it costs them a round trip and reports our form instead of their antivirus. It also runs end to end under pwsh on Linux, where every Windows-only facility reports itself unavailable and nothing crashes. - That guard earned itself immediately: the first draft put the script in a YAML **folded** scalar (`>`), which joins every line and silently collapsed the whole code block to nothing. The test catches that specific mistake and names it as the likely cause. - Both new guards confirmed to bite: reverting the scalar to `>` fails three tests, and making `detection-name` optional fails with the reason the field exists.
…hine `install.sh` generates a PowerShell script and runs it on the Windows side to create the WSL shortcut. Two constructs in that path were removed from `install.ps1` in earlier passes and left live here, where nothing looked: - `install.sh:2249` declared `SHChangeNotify` with `Add-Type -MemberDefinition`. On Windows PowerShell 5.1 that writes C# to `%TEMP%` and runs `csc.exe`, producing a DLL on the user's machine. #10540 traced exactly that chain to Bitdefender `Gen:Variant.MSILHeracles.272113`: `unsloth-stud... -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll`. It replaced the declaration in `install.ps1` with reflection emit and missed this copy. - `install.sh:2273` launched the generated script with `-ExecutionPolicy Bypass`, the flag #7822 removed everywhere else. Neither was caught because `test_the_installer_never_runs_the_c_sharp_compiler` parametrised over `("install.ps1", "studio/setup.ps1")` only, and `windows-no-compiler-ci.yml` did not list `install.sh` in its path triggers. A shell script that emits PowerShell can put a compiler on a Windows machine without touching a `.ps1`. ## The compile `SHChangeNotify` is now emitted, mirroring `install.ps1:3485-3499`: a `DefineDynamicAssembly` / `DefineDynamicModule` / `DefineType` / `DefinePInvokeMethod` / `CreateType` block inlined, since the generated script is standalone and cannot call `New-StudioEmittedNativeType`. The enclosing `try {} catch {}` stays, so a failure still costs only a stale icon, and both notifications stay: per-item `SHCNE_UPDATEITEM` + `SHCNF_PATHW` per `.lnk`, then the global `SHCNE_ASSOCCHANGED`. The per-item call is not redundant, and the `ALLOWED_PINVOKES` entry records why: `ie4uinit.exe -show` does not recover a stale same-name `.lnk`. I ran the emitted type rather than assuming it: under pwsh it produces `void SHChangeNotify(Int32, UInt32, String, IntPtr)`, identical to the `Add-Type` declaration, `PreserveSig` set, and `Assembly.Location` empty, which is the point. Nothing reaches disk. ## The execution policy `Bypass` was load-bearing, for one reason: `wslpath -w /tmp/unsloth-shortcut-XXXXXX.ps1` yields a `\\wsl.localhost\<distro>\...` UNC path, PowerShell treats a script there as remote, and `RemoteSigned` refuses an unsigned remote script. So rather than relax the policy, the script now goes to the Windows `%TEMP%` (`cmd.exe /c echo %TEMP%`, CR stripped, `wslpath -u`), which is a local volume and therefore `MyComputer` zone, where `RemoteSigned` loads it unsigned. Same generated script, same launch, same result. When `%TEMP%` cannot be resolved there is deliberately **no fallback to WSL's `/tmp`**, because that is the case that needed the relaxed policy in the first place. Nothing is allocated and the caller takes the notice it already prints when interop is unavailable. That population is very nearly the population where interop is already broken. ## Tripwires, with messages that say what is wrong `tests/sh/test_wsl_shortcut_script_location.sh` evals the real resolution block out of `install.sh` with `cmd.exe` and `wslpath` stubbed, covering resolved, no-interop, unexpanded `%TEMP%`, and a `%TEMP%` that is not a directory, then asserts statically that the launch uses `RemoteSigned`, that the file relaxes the policy nowhere, that it compiles no C#, and that both refreshes survive. A failed extraction is reported as a failure rather than exiting early, so the output names every problem at once, and it still fails closed. `clean-machine-install-ci.yml`'s `wsl` job is the only lane that runs this branch, so it gains the behavioural half: read the created `.lnk` back and refuse a script-host target, require the generated script to have been cleaned up, and fail on any `.cmdline`/`.rsp` under the Windows `%TEMP%`, which is csc.exe output and nothing else. That check plants two intermediates and requires the search to find both before trusting a negative result, because a detector that sees nothing looks exactly like a clean run and every reason it might see nothing is silent. If the control does not fire the job fails as a broken detector instead of reporting a pass. Shortcut absence is a warning, not an error, since the installer itself treats shortcut creation as best-effort. `install.sh` is added to the compiler test's parametrise list and to `windows-no-compiler-ci.yml`'s paths. The `DefinePInvokeMethod` assertion in that test becomes conditional on the file declaring a native import at all, so it does not fail for being satisfied on `scripts/uninstall.ps1` or `studio/setup.sh`. ## Verification - The new shell suite: 16 passed on this branch, and against `main` in a worktree it exits 1 with 6 named failures. Proved to bite rather than assumed to. - The generated WSL script rendered and parsed with `[System.Management.Automation.Language.Parser]::ParseFile`: clean over 765 tokens. No existing gate parses that here-string, and this change edits it. - `bash -n` and `sh -n` on `install.sh`; all of `tests/sh` passing; the parse gate clean over `install.ps1`, `studio/setup.ps1` and `scripts/uninstall.ps1`. - `tests/studio/test_installer_av_shapes.py`, `tests/studio/install/`, `tests/security/`: green. - The new CI PowerShell parsed standalone, and its positive control plus detector exercised for real against a planted `csc.exe`-style intermediate: control 2 of 2, simulated compile caught, clean directory reports zero. I have no Windows or WSL here, so the runtime behaviour of the shortcut path rests on the `clean-machine-install-ci.yml` WSL job, not on a local run. This is a shape fix with a confirmed detection behind the shape; it is not a claim that any particular user report is resolved.
…scarding the packets Every report of security software blocking Unsloth (#8523, #6326, #6588, #6648, #10540, #10805) named no antivirus product, no detection name and no AMSI provider. Clearance is per hash and vendors act on a detection name, so not one of those reports could be submitted anywhere, and not one of the six hardening passes since can be shown to have fixed what it aimed at. That is the gap here. ## A required-field issue form `.github/ISSUE_TEMPLATE/install-blocked-windows.yml`, a form rather than a markdown template for one reason: a form can mark a field `required` and a template cannot. Required: the product and version, the detection name exactly as displayed, the full error including the `FullyQualifiedErrorId` line, and the output of a collection script. Also a dropdown separating "the script would not run at all" from "something it created was blocked", because those are different mechanisms with different fixes and have been conflated in past reports. The script reads registered antivirus products from `root/SecurityCenter2`, resolves each AMSI provider CLSID through `InprocServer32` to a DLL and reads its `CompanyName`/`ProductName`/version, then `Get-MpComputerStatus` and recent Defender events. The provider resolution is the part that actually answers "which product", since a bare CLSID is not actionable. So is `AMRunningMode`: anything other than `Normal` means another product is primary. It downloads nothing, writes nothing, and changes nothing -- and it deliberately carries none of the shapes the installers are being cleaned of, because a diagnostic that trips the same product that blocked the installer is worthless. A test enforces that: no `Add-Type`, no `Invoke-Expression`, no base64, no `Set-MpPreference`, no `Remove-Item`, no `Start-Process`. ## The packets that were being thrown away Two false-positive submission packets are built today and discarded. `release-desktop.yml` writes a Microsoft submission packet to `$RUNNER_TEMP` and never uploads it, so `flagged-windows-bundles-*` held the flagged bundles and nothing describing them; it is now included in that artifact. And `scripts/virustotal_scan.py`'s packet went only into a job summary, which is ephemeral, so the one document written for the purpose of disputing a detection was discarded along with the run; it is now kept as an artifact. Retention on the flagged bundles goes from 7 days to 90. Clearance is per hash and a rebuild hashes differently, so those copies are the only submittable sample for that release, and a vendor round trip plus our own reaction routinely outlasts a week -- after which the evidence for the detection being disputed is gone. `test_the_scan_job_is_not_conditioned_away` allowed `if: always()` on exactly one step. The new upload needs it for the identical stated reason, "precisely so the evidence survives a failed scan", so the exception becomes a named set of two rather than a shape a future step could inherit by resembling. ## Verification - 675 passed, 6 skipped across `tests/security/` and `tests/python/test_virustotal_scan.py`. - The collection script is extracted from the YAML and **parsed**, not eyeballed. It is pasted verbatim by people who are already stuck, so a syntax error in it costs them a round trip and reports our form instead of their antivirus. It also runs end to end under pwsh on Linux, where every Windows-only facility reports itself unavailable and nothing crashes. - That guard earned itself immediately: the first draft put the script in a YAML **folded** scalar (`>`), which joins every line and silently collapsed the whole code block to nothing. The test catches that specific mistake and names it as the likely cause. - Both new guards confirmed to bite: reverting the scalar to `>` fails three tests, and making `detection-name` optional fails with the reason the field exists.
…ch antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. ## The split - A comment in a shipped script says **what the code does and what breaks if you change it**. - `docs/windows-installer-av-shapes.md` says **which scanner flagged which shape, and when**. Each relocated comment keeps its operational content verbatim and gains an anchor link. Nothing about what any script does changes: the diff over the five shipped scripts contains no non-comment line, which is mechanically checked rather than asserted. The document is not a dumping ground. It records the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. It is not packaged: not a package directory, not in `MANIFEST.in`, not in `bundle.resources`. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. ## The guards A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_shapes_document_exists_and_keeps_its_anchors`, which also requires the specific detection strings to still be recorded -- a document with anchors and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_document`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. ## Verification - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files (41210 / 39413 / 6696 tokens). - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing.
…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.
…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.
…ch antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. ## The split - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. ## The guards A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. ## Verification - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again.
…ch antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. ## The split - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. ## The guards A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. ## Verification - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again.
…ch antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. ## The split - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. ## The guards A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. ## Verification - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again.
…ch antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again.
…eady deleted The lane looked for .cmdline and .rsp files in the Windows temp after the install had finished. CodeDom removes its whole intermediate directory once the assembly is loaded, which Watch-ForCompiler.ps1 records as a before-and-after diff seeing nothing at all while 4688 recorded csc.exe, so that search could not fail for the case this lane exists to catch. Its positive control planted persistent files, which proves the search can traverse a directory and nothing about whether ephemeral compiler output is observable. The install now runs inside Invoke-WithCompilerWatch, the same detector windows-no-compiler-ci.yml uses, which unions 4688 with a live FileSystemWatcher and treats an unreadable Security log as void rather than clean. The dropped-library half is checked too, since that is what the Bitdefender report in #10540 keyed on. The post-hoc listing stays for what genuinely is left behind, which is the other half of the union, and its message now says that is what it means. Watch-ForCompiler.ps1 is in both path filters now, because this job's detection depends on it, and the new guard is registered in the unfiltered lint job since it reads a workflow file.
…ch antivirus flagged them (#10990) * Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Match banned vendor tokens on word boundaries, and drop the one that cannot work The guard searched for each token as a raw substring, so it rejected ordinary installer prose: 'panda' is inside 'pandas', a real dependency name, and 'rising' is inside 'surprising', 'arising' and 'comprising'. The failure message then accuses a normal sentence of naming an antivirus vendor, and the fix the next reader reaches for is to delete the guard. Boundaries are conditional on the token's own edges, because 'heur:' and 'gen:variant' sit on a colon where \b asserts the opposite of what is wanted. 'rising' is removed rather than bounded. It is a real engine and one of the two that flagged the fixture archives, but the word is also ordinary English -- 'rising memory use' is a sentence someone will write -- and no amount of boundary matching separates the two. A guard that fails on valid prose is worth less than nothing. 'tencent', the other engine that flagged those archives, has no such problem and stays. Verified both directions against studio/setup.sh: a comment naming Bitdefender, Gen:Variant and Panda still produces three failures, while 'rising memory use' plus 'installs pandas' now passes and produced two misleading failures before. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…igned (#10982) * AV shape guards: watch the two shipped scripts nothing watched, and ratchet the policy sites Stacked on the WSL compiler fix, which shares this file. Two problems, both found while investigating #10805, and both about the guard rather than the code it guards. ## Two shipped scripts were in no list `PS_SCRIPTS` and `SH_SCRIPTS` between them missed `studio/setup.bat` and `scripts/uninstall.sh`. A shipped `.bat` is scanned like any other file, and `setup.bat` launches PowerShell, so every rule here applies to it. That is how its `-ExecutionPolicy Bypass` survived the passes in #7822 and #8586: the guards were reading a set of files that did not include it. Both are added to `ALL_SCRIPTS`. ## The hidden-window pair check only ever looked at one line `test_a_hidden_window_never_pairs_with_a_bypassed_policy` iterated `splitlines()` and compared the two flags within a single physical line. `install.ps1` assigns `$shortcutArgs` a hidden window at :3419 and overwrites it with a relaxed policy at :3433, fourteen lines apart in the same function, and that passed for as long as it existed. A scanner reads the file, not the line. Three layers now: 1. Same line, unchanged, because it gives the clearest message when it is the real shape. 2. A ratchet on how many relaxed policies the file contains at all, against `KNOWN_BYPASS_SITES`, which records each remaining site with the reason and what would remove it. It fails **both** ways: too many is a new site, too few is a stale entry that has quietly stopped guarding anything. This is the layer that catches a policy arriving somewhere the other two do not model. 3. Same variable, any distance: the union of everything assigned to one name must not contain both flags. This is the layer that sees the 3419/3433 shape. `install.ps1`'s `$shortcutArgs` is recorded in `KNOWN_SPLIT_PAIR_VARIABLES` rather than failed on. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, because `%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned refuses an unsigned script, and a shortcut that silently does nothing is worse than the token. Recording it lets the guard land now and lock in "no new ones", which is the part that matters going forward. ## Verification 70 passed in the suite, and each new layer was confirmed to bite rather than assumed to: - A new relaxed policy injected into `studio/setup.sh` fails layer 2, naming the file, line number, the offending line, and what to do about it. - Removing the recorded site from `studio/setup.bat` without lowering its count fails layer 2 the other way, telling the reader to lower the count in the same commit. - Layer 3 proved in isolation by renaming `$shortcutArgs` to `$launchArgs` in `install.ps1`: the relaxed-policy count is unchanged so layer 2 passes, and layer 3 fires on its own. The tree was restored after each and re-verified clean. `tests/studio/install/` and the shape suite are green; `test_pr10648_offline_and_status.py::test_the_pr_only_added_new_arms_to_the_setup_status_blocks` fails identically on `main` in a separate worktree and is untouched by this change. * Load the installer scripts under RemoteSigned instead of relaxing the policy Removes three of the four relaxed execution policies the ratchet in the previous commit recorded. RemoteSigned refuses an unsigned script only in the Internet or Untrusted zone, so for a local, unmarked script it behaves identically to Bypass while dropping a token endpoint products score. ## studio/setup.bat `powershell -ExecutionPolicy Bypass -File "%~dp0setup.ps1"` becomes RemoteSigned. setup.ps1 ships beside the batch file inside an installed package, so it is MyComputer-zone and loads unsigned either way. One population could regress: a package unzipped from a download, where setup.ps1 carries a mark of the web that RemoteSigned honours and Bypass ignored. So the mark is cleared first. Execution policy governs script *files* and not `-Command`, so that call runs under any machine policy, and clearing an absent stream writes nothing. The path travels in an environment variable rather than being interpolated into the command string, because an apostrophe in an install path is a real Windows user name and would otherwise break the quoting. `-NoProfile` is on the unblock call and deliberately **not** on the launch. The launch has always run setup.ps1 with profiles loaded, and `tests/studio/test_amd_venv_repair_loop.ps1` drives a profile that sets `Set-StrictMode -Version Latest` against it. Adding the flag would have retired that coverage with nothing failing, so the new test asserts its absence and says why. ## scripts/uninstall.ps1 and README.md Both print `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` as the documented way to run a cloned script. Changed to RemoteSigned rather than dropped: the Windows client default is `Restricted`, which blocks every script file including a local unsigned one, so the `Set-ExecutionPolicy` itself is load-bearing and removing it would break the documented path. RemoteSigned is sufficient because a git clone carries no mark of the web, and both now say so and point a zip user at `Unblock-File`, which is the case where the two policies genuinely differ. The uninstaller line is never executed -- it lives in the printed `_Usage` here-string -- but AMSI scans the file whole and a classifier cannot tell a string from a statement. ## Where that leaves the ratchet Four recorded sites down to one. The survivor is `install.ps1:3433`, the roaming-profile fallback for a launcher on a share, and it stays because `%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned would refuse the launcher, and a desktop shortcut that silently does nothing is worse than the token. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, which is a larger change than this one. ## Verification - 751 passed, 6 skipped across the shape suite, `tests/test_installer_interactive_prompts.py` and `tests/security/`. All of `tests/sh` passing. The parse gate clean over all three `.ps1` files. - Both new `setup.bat` assertions confirmed to bite: adding `-NoProfile` to the launch fails with the reason and names the test that would lose coverage, and reverting the policy to Bypass fails naming the offending line. The tree was restored after each. - Relaxed-policy sites counted directly across all seven shipped scripts afterwards: one, in install.ps1, as recorded. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Step setup.bat down to Bypass for a script on a share, the way install.ps1 already does Tightening setup.bat from Bypass to RemoteSigned had one case that is a genuine regression rather than a theoretical one, and it needed handling rather than accepting. Execution policy is judged on the script file's ZONE. A plain \\server\share and a mapped drive are Intranet and load fine under RemoteSigned -- but a dotted-FQDN UNC (\\corp.example.com\...), a DFS path or an IP-literal share is the Internet zone, where RemoteSigned refuses an unsigned script. And Unblock-File cannot save that case: with no Zone.Identifier stream present the PATH decides, so clearing a stream that was never there changes nothing and exits silently. Bypass worked; RemoteSigned does not. install.ps1:3405-3421 already solves exactly this when it writes the Start Menu shortcut -- UNC prefix, then DriveInfo.DriveType -eq 'Network' -- and the new test's own comment calls that site "the only one that is genuinely load-bearing" for the same reason. setup.bat got no such exemption. Now it reuses the identical logic rather than inventing a second answer. The probe does the Unblock-File too, so this costs one process rather than two, and it runs under -Command, which execution policy does not govern at all. Two details that matter more than they look: - The batch variable DEFAULTS to RemoteSigned. A probe that fails to run therefore leaves the tightened policy in place rather than silently restoring the relaxed one. - -NoProfile is on the probe and still deliberately absent from the launch. tests/studio/test_amd_venv_repair_loop.ps1 drives a profile that sets Set-StrictMode against setup.ps1, and adding it would retire that coverage with nothing failing. Tests: the embedded probe is extracted from the batch file and PARSED, because it is one long line inside a `for /f` backquote block and a syntax error there fails quietly -- the `for /f` captures nothing, the RemoteSigned default stands, and the mark is never cleared, so an unzipped download gets a refusal with no hint that the probe was what broke. The pre-existing setup.bat test located the launch by literal filename, which is now an environment variable, so it matches on the flags instead. 5713 passed, 39 skipped across tests/studio/test_installer_av_shapes.py, tests/studio/install/ and tests/security/. The single failure, test_pr10648_offline_and_status, is pre-existing on main. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Group the hidden/bypass pair by casefolded variable name PowerShell variable names are not case-sensitive, so $shortcutArgs and $ShortcutArgs are one variable. The same-variable layer keyed its map on the captured spelling, so writing the two assignments with different capitalisation filed them as two unrelated names, each holding only one of the two flags, and the pair went through. The file-wide ratchet did not catch it either, since install.ps1 already records one permitted relaxed policy. Verified by constructing that exact evasion: renaming the two install.ps1 assignments to $launchArgs and $LaunchArgs passes under the old grouping and fails under this one, naming both spellings. * Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them (#10990) * Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Match banned vendor tokens on word boundaries, and drop the one that cannot work The guard searched for each token as a raw substring, so it rejected ordinary installer prose: 'panda' is inside 'pandas', a real dependency name, and 'rising' is inside 'surprising', 'arising' and 'comprising'. The failure message then accuses a normal sentence of naming an antivirus vendor, and the fix the next reader reaches for is to delete the guard. Boundaries are conditional on the token's own edges, because 'heur:' and 'gen:variant' sit on a colon where \b asserts the opposite of what is wanted. 'rising' is removed rather than bounded. It is a real engine and one of the two that flagged the fixture archives, but the word is also ordinary English -- 'rising memory use' is a sentence someone will write -- and no amount of boundary matching separates the two. A guard that fails on valid prose is worth less than nothing. 'tencent', the other engine that flagged those archives, has no such problem and stays. Verified both directions against studio/setup.sh: a comment naming Bitdefender, Gen:Variant and Panda still produces three failures, while 'rising memory use' plus 'installs pandas' now passes and produced two misleading failures before. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…op discarding the false-positive submission packets (#10986) * Capture the evidence six reports of this never contained, and stop discarding the packets Every report of security software blocking Unsloth (#8523, #6326, #6588, #6648, #10540, #10805) named no antivirus product, no detection name and no AMSI provider. Clearance is per hash and vendors act on a detection name, so not one of those reports could be submitted anywhere, and not one of the six hardening passes since can be shown to have fixed what it aimed at. That is the gap here. ## A required-field issue form `.github/ISSUE_TEMPLATE/install-blocked-windows.yml`, a form rather than a markdown template for one reason: a form can mark a field `required` and a template cannot. Required: the product and version, the detection name exactly as displayed, the full error including the `FullyQualifiedErrorId` line, and the output of a collection script. Also a dropdown separating "the script would not run at all" from "something it created was blocked", because those are different mechanisms with different fixes and have been conflated in past reports. The script reads registered antivirus products from `root/SecurityCenter2`, resolves each AMSI provider CLSID through `InprocServer32` to a DLL and reads its `CompanyName`/`ProductName`/version, then `Get-MpComputerStatus` and recent Defender events. The provider resolution is the part that actually answers "which product", since a bare CLSID is not actionable. So is `AMRunningMode`: anything other than `Normal` means another product is primary. It downloads nothing, writes nothing, and changes nothing -- and it deliberately carries none of the shapes the installers are being cleaned of, because a diagnostic that trips the same product that blocked the installer is worthless. A test enforces that: no `Add-Type`, no `Invoke-Expression`, no base64, no `Set-MpPreference`, no `Remove-Item`, no `Start-Process`. ## The packets that were being thrown away Two false-positive submission packets are built today and discarded. `release-desktop.yml` writes a Microsoft submission packet to `$RUNNER_TEMP` and never uploads it, so `flagged-windows-bundles-*` held the flagged bundles and nothing describing them; it is now included in that artifact. And `scripts/virustotal_scan.py`'s packet went only into a job summary, which is ephemeral, so the one document written for the purpose of disputing a detection was discarded along with the run; it is now kept as an artifact. Retention on the flagged bundles goes from 7 days to 90. Clearance is per hash and a rebuild hashes differently, so those copies are the only submittable sample for that release, and a vendor round trip plus our own reaction routinely outlasts a week -- after which the evidence for the detection being disputed is gone. `test_the_scan_job_is_not_conditioned_away` allowed `if: always()` on exactly one step. The new upload needs it for the identical stated reason, "precisely so the evidence survives a failed scan", so the exception becomes a named set of two rather than a shape a future step could inherit by resembling. ## Verification - 675 passed, 6 skipped across `tests/security/` and `tests/python/test_virustotal_scan.py`. - The collection script is extracted from the YAML and **parsed**, not eyeballed. It is pasted verbatim by people who are already stuck, so a syntax error in it costs them a round trip and reports our form instead of their antivirus. It also runs end to end under pwsh on Linux, where every Windows-only facility reports itself unavailable and nothing crashes. - That guard earned itself immediately: the first draft put the script in a YAML **folded** scalar (`>`), which joins every line and silently collapsed the whole code block to nothing. The test catches that specific mistake and names it as the likely cause. - Both new guards confirmed to bite: reverting the scalar to `>` fails three tests, and making `detection-name` optional fails with the reason the field exists. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Upload the submission packet after the step that writes it, and make the form's labels real Two defects found reviewing this PR, both of which would have failed silently. ## The packet was uploaded sixty lines before it was written `Preserve flagged Windows bundles` is step 24; the packet is assembled in step 26. Steps run top to bottom, so `${{ runner.temp }}/ms-submission-packet.md` never existed when that upload ran -- and `if-no-files-found: ignore` would have hidden it permanently. The artefact meant to carry a vendor submission would have held the flagged bundles and nothing describing them, which is the exact failure this PR exists to fix, reintroduced one step higher up. The packet now has its own upload step immediately after the step that writes it. The path is removed from the earlier step rather than left in as harmless, because a path that cannot match is a claim the file is covered. Removing it also avoids a side effect worth knowing: upload-artifact computes the artefact root from glob pattern prefixes rather than matched files, so the second path would have re-rooted that zip from flat to nested. `if-no-files-found: ignore`, not `warn`: the packet is only assembled when there is something to submit, so its absence on a clean release is the normal case and must not add an annotation to every green run. ## Two of the form's three labels did not exist `windows` and `antivirus-false-positive` were not among the repository's labels. GitHub does not error on an unknown label, it drops it -- so every issue filed through this form would have arrived with `bug` only, losing precisely the two triage labels the form exists to attach, with nothing reporting the loss. Both labels now exist on the repository, and `test_the_labels_the_form_declares_are_real` keeps the form and the repository in step. It checks against a checked-in list rather than the GitHub API, because a test that needs the network is a test that gets skipped. * Start pwsh through the shared runner here too Same reason as the sibling fix in the AMSI probe lane: tests/studio/test_pwsh_calls_use_the_shared_runner.py bans a direct subprocess call to pwsh, because a direct one shares a single $XDG_CACHE_HOME/powershell startup cache with every xdist worker and an interpreter that dies at startup then reads as the script under test having failed. Caught only by running the full suite against all ten open PRs merged into one tree; the guard lives in tests/studio/ and never ran against this branch alone. * Redact the profile directory and account name before the report is published The collection block is a required field, so its output goes into a public issue, and it printed Path and Process Name for every Defender detection in the last two hours whether or not it had anything to do with Unsloth. On a normal machine those paths begin with the profile directory and therefore carry the account name, and the file name can be anything the person had open. The description also promised it touched no personal data, which was not true. Redact at the point of printing rather than asking the reporter to do it, since the reporter is someone whose install is already broken and who is pasting a block they did not write. Say plainly what is still printed and tell them to read it first. Verified against paths with a space in the name and with mismatched case. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Match the Defender event fields, which are indented Defender renders 1116 and its siblings as a header line followed by indented 'Field: value' lines, so anchoring on '^Name:' matched none of them and the section that exists to carry the detection name, the path and the triggering process emitted a timestamp and an event id and nothing else. Measured against a message in the documented shape: the old filter selects the empty string, the new one selects all six fields. Severity is included now too, since it is free once the line is being read and it is the field that tells us whether a report is a block or a warning. The guard drives the snippet's own filter rather than asserting the regex text, so a future rewrite is judged on what it extracts. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Give screenshots their own field, survive localised Defender labels, warn on the error field too A render: textarea wraps everything it contains in a code fence, attachments included, so the error field invited a screenshot it could never display. It keeps render: text, because it carries pasted console output where the monospace block earns its place, and screenshots get their own unrendered field. Defender localises the event field labels, so the English-only filter missed them and a non-English reporter would have sent a timestamp and an event id. Testing for an empty result is not enough: German renders Name: identically, so one match out of six looks like a successful extraction. The fallback counts instead, and prints the whole message, redacted and truncated, when fewer than two fields resolve. Measured on English, German and Japanese messages. The privacy note covered the probe output only. A PowerShell error quotes the script's location, so on the documented cloned-checkout path the required error field carries the reporter's user name and they are told to paste it verbatim before they reach that note. It now says the issue is public and suggests the substitution. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Warn on the issue form field that asks for a full path The error and probe fields say the issue is public and show what to write instead, but the file path field asked for a full path with only a profile-shaped placeholder to follow, so a reporter doing what it says publishes their user name. Give it the same warning and the same worked replacement. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Redact only real account components, and scope the probe's error preference The username replacement rewrote every case-insensitive occurrence anywhere in the line, so an account named win rewrote Windows Defender and one named cat rewrote Wacatac. Those are the product and detection names the form exists to collect, and the reporter cannot see it happen. Require a path separator before the name and no word character after it. The probe also set ErrorActionPreference at the prompt, which persists for the rest of that session, against the field's own promise that it changes nothing. Run the body in a script block so the assignment is scoped to it. * [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>
…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>
The control checked only the process half, so a FileSystemWatcher that never attached, or stopped reporting creations, looked exactly like a run that dropped no library. TempLibraries is the half the Bitdefender report in #10540 keyed on, and the install below trusts it. Require both, as windows-no-compiler-ci.yml already does.
…hine (#10978) * WSL installer: stop running the C# compiler on the user's Windows machine `install.sh` generates a PowerShell script and runs it on the Windows side to create the WSL shortcut. Two constructs in that path were removed from `install.ps1` in earlier passes and left live here, where nothing looked: - `install.sh:2249` declared `SHChangeNotify` with `Add-Type -MemberDefinition`. On Windows PowerShell 5.1 that writes C# to `%TEMP%` and runs `csc.exe`, producing a DLL on the user's machine. #10540 traced exactly that chain to Bitdefender `Gen:Variant.MSILHeracles.272113`: `unsloth-stud... -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll`. It replaced the declaration in `install.ps1` with reflection emit and missed this copy. - `install.sh:2273` launched the generated script with `-ExecutionPolicy Bypass`, the flag #7822 removed everywhere else. Neither was caught because `test_the_installer_never_runs_the_c_sharp_compiler` parametrised over `("install.ps1", "studio/setup.ps1")` only, and `windows-no-compiler-ci.yml` did not list `install.sh` in its path triggers. A shell script that emits PowerShell can put a compiler on a Windows machine without touching a `.ps1`. ## The compile `SHChangeNotify` is now emitted, mirroring `install.ps1:3485-3499`: a `DefineDynamicAssembly` / `DefineDynamicModule` / `DefineType` / `DefinePInvokeMethod` / `CreateType` block inlined, since the generated script is standalone and cannot call `New-StudioEmittedNativeType`. The enclosing `try {} catch {}` stays, so a failure still costs only a stale icon, and both notifications stay: per-item `SHCNE_UPDATEITEM` + `SHCNF_PATHW` per `.lnk`, then the global `SHCNE_ASSOCCHANGED`. The per-item call is not redundant, and the `ALLOWED_PINVOKES` entry records why: `ie4uinit.exe -show` does not recover a stale same-name `.lnk`. I ran the emitted type rather than assuming it: under pwsh it produces `void SHChangeNotify(Int32, UInt32, String, IntPtr)`, identical to the `Add-Type` declaration, `PreserveSig` set, and `Assembly.Location` empty, which is the point. Nothing reaches disk. ## The execution policy `Bypass` was load-bearing, for one reason: `wslpath -w /tmp/unsloth-shortcut-XXXXXX.ps1` yields a `\\wsl.localhost\<distro>\...` UNC path, PowerShell treats a script there as remote, and `RemoteSigned` refuses an unsigned remote script. So rather than relax the policy, the script now goes to the Windows `%TEMP%` (`cmd.exe /c echo %TEMP%`, CR stripped, `wslpath -u`), which is a local volume and therefore `MyComputer` zone, where `RemoteSigned` loads it unsigned. Same generated script, same launch, same result. When `%TEMP%` cannot be resolved there is deliberately **no fallback to WSL's `/tmp`**, because that is the case that needed the relaxed policy in the first place. Nothing is allocated and the caller takes the notice it already prints when interop is unavailable. That population is very nearly the population where interop is already broken. ## Tripwires, with messages that say what is wrong `tests/sh/test_wsl_shortcut_script_location.sh` evals the real resolution block out of `install.sh` with `cmd.exe` and `wslpath` stubbed, covering resolved, no-interop, unexpanded `%TEMP%`, and a `%TEMP%` that is not a directory, then asserts statically that the launch uses `RemoteSigned`, that the file relaxes the policy nowhere, that it compiles no C#, and that both refreshes survive. A failed extraction is reported as a failure rather than exiting early, so the output names every problem at once, and it still fails closed. `clean-machine-install-ci.yml`'s `wsl` job is the only lane that runs this branch, so it gains the behavioural half: read the created `.lnk` back and refuse a script-host target, require the generated script to have been cleaned up, and fail on any `.cmdline`/`.rsp` under the Windows `%TEMP%`, which is csc.exe output and nothing else. That check plants two intermediates and requires the search to find both before trusting a negative result, because a detector that sees nothing looks exactly like a clean run and every reason it might see nothing is silent. If the control does not fire the job fails as a broken detector instead of reporting a pass. Shortcut absence is a warning, not an error, since the installer itself treats shortcut creation as best-effort. `install.sh` is added to the compiler test's parametrise list and to `windows-no-compiler-ci.yml`'s paths. The `DefinePInvokeMethod` assertion in that test becomes conditional on the file declaring a native import at all, so it does not fail for being satisfied on `scripts/uninstall.ps1` or `studio/setup.sh`. ## Verification - The new shell suite: 16 passed on this branch, and against `main` in a worktree it exits 1 with 6 named failures. Proved to bite rather than assumed to. - The generated WSL script rendered and parsed with `[System.Management.Automation.Language.Parser]::ParseFile`: clean over 765 tokens. No existing gate parses that here-string, and this change edits it. - `bash -n` and `sh -n` on `install.sh`; all of `tests/sh` passing; the parse gate clean over `install.ps1`, `studio/setup.ps1` and `scripts/uninstall.ps1`. - `tests/studio/test_installer_av_shapes.py`, `tests/studio/install/`, `tests/security/`: green. - The new CI PowerShell parsed standalone, and its positive control plus detector exercised for real against a planted `csc.exe`-style intermediate: control 2 of 2, simulated compile caught, clean directory reports zero. I have no Windows or WSL here, so the runtime behaviour of the shortcut path rests on the `clean-machine-install-ci.yml` WSL job, not on a local run. This is a shape fix with a confirmed detection behind the shape; it is not a claim that any particular user report is resolved. * Fix a test of mine that passed for the wrong reason, and could only fail on a real CI machine `test_wsl_shortcut_script_location.sh` asserted that the generated shortcut script's path does not start with `/tmp`, as a proxy for "not in WSL's own temp, which wslpath turns into a \\wsl.localhost UNC path that RemoteSigned refuses". The proxy is broken: the harness builds its *fake Windows temp* with `mktemp -d`, so on any machine with `TMPDIR=/tmp` -- which is every normal CI runner -- the stub's own directory matched the pattern and the test failed while install.sh was behaving exactly as intended. It passed locally only because this workspace sets `TMPDIR` elsewhere. That is precisely the class of accidental pass the rest of this work has been built to catch, so it is worth naming rather than quietly correcting. The replacement asserts the property the proxy was standing in for, structurally: the block contains exactly one `mktemp`, so there is no second path to fall back to, and that `mktemp` allocates inside `$_css_win_temp`. Both are true or false regardless of where anyone's temp directory happens to live. Verified under the exact condition that broke it: `TMPDIR=/tmp` gives 17 passed, 0 failed on this branch, and 6 failed on `main` in a clean worktree -- so the test still bites. * WSL installer: read %TEMP% with cmd /d, so an AutoRun command cannot cost the user their shortcut Reading the Windows %TEMP% through interop is new in this branch, and it reads it with `cmd.exe /c echo %TEMP%`. Without /d, cmd first runs the AutoRun command from HKLM or HKCU \Software\Microsoft\Command Processor, and `cmd /c` is not exempt from that. AutoRun writes to the same stdout, so its output arrives ahead of the path and `tr -d '\r\n'` glues the two into one string. wslpath then rejects it, the directory check fails, and the branch takes its "couldn't create the Windows shortcut" notice. Clink sets an AutoRun, so Cmder does, and so do plenty of corporate images. Every one of those users got a working shortcut before this branch and would silently stop getting one, while being told WSL interop is disabled, which is not what happened. So: /d, which is the cheap fix rather than out-parsing whatever prints. Then the last line rather than the whole stream, for anything that still reaches stdout by another route, and trailing blanks trimmed, because Win32 strips them from a path and [ -d ] does not, so a %TEMP% set with one resolved to a directory that appeared not to exist. The || stays: this file runs under set -e, where a failed substitution ends the install. Tests ----- tests/sh/test_wsl_shortcut_script_location.sh grows the AutoRun and trailing-blank cases and a static check for /d, and its wslpath stub is now input-sensitive. It was not, and that mattered: a stub that returns the fake Windows temp whatever it is handed cannot tell "install.sh read the path" from "install.sh read a banner glued to a path", so both new cases passed against the unfixed file until the stub compared its argument. Against the unfixed install.sh the four new assertions fail; with it they pass. tests/studio/test_wsl_shortcut_script_is_valid_powershell.py is new and covers a gap nothing else did: that what install.sh generates is PowerShell at all. bash -n sees the here-string as a here-string, the contents only run on Windows with both streams sent to /dev/null, and the icon-refresh block runs inside try/catch, so a parse error there is not a crash and not a message, just no shortcut and a misleading notice. The block was just rewritten into a twenty-line reflection-emit sequence, which is when that matters most. The file renders the here-string with a real shell rather than keeping a copy, parses it, and then executes the emit sequence retargeted at a symbol this host exports, so a wrong call order or argument count fails on Linux. Five mutations of the shipped file were tried; four fail it, and the docstring names the fifth that does not and why. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Watch the WSL install live, instead of searching for what CodeDom already deleted The lane looked for .cmdline and .rsp files in the Windows temp after the install had finished. CodeDom removes its whole intermediate directory once the assembly is loaded, which Watch-ForCompiler.ps1 records as a before-and-after diff seeing nothing at all while 4688 recorded csc.exe, so that search could not fail for the case this lane exists to catch. Its positive control planted persistent files, which proves the search can traverse a directory and nothing about whether ephemeral compiler output is observable. The install now runs inside Invoke-WithCompilerWatch, the same detector windows-no-compiler-ci.yml uses, which unions 4688 with a live FileSystemWatcher and treats an unreadable Security log as void rather than clean. The dropped-library half is checked too, since that is what the Bitdefender report in #10540 keyed on. The post-hoc listing stays for what genuinely is left behind, which is the other half of the union, and its message now says that is what it means. Watch-ForCompiler.ps1 is in both path filters now, because this job's detection depends on it, and the new guard is registered in the unfiltered lint job since it reads a workflow file. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Arm the 4688 half of the compiler watch in the WSL lane Watch-ForCompiler.ps1 requires the caller to enable process creation auditing, and this job never did, so its Security log query returned an empty compiler list whatever ran while the step still printed that no compiler process was seen. Enable and verify the audit policy before the install, and require a deliberate compile to be detected first, so a clean verdict is distinguishable from a detector that never attached. * Close the AV shape-guard holes, and load the installers under RemoteSigned (#10982) * AV shape guards: watch the two shipped scripts nothing watched, and ratchet the policy sites Stacked on the WSL compiler fix, which shares this file. Two problems, both found while investigating #10805, and both about the guard rather than the code it guards. ## Two shipped scripts were in no list `PS_SCRIPTS` and `SH_SCRIPTS` between them missed `studio/setup.bat` and `scripts/uninstall.sh`. A shipped `.bat` is scanned like any other file, and `setup.bat` launches PowerShell, so every rule here applies to it. That is how its `-ExecutionPolicy Bypass` survived the passes in #7822 and #8586: the guards were reading a set of files that did not include it. Both are added to `ALL_SCRIPTS`. ## The hidden-window pair check only ever looked at one line `test_a_hidden_window_never_pairs_with_a_bypassed_policy` iterated `splitlines()` and compared the two flags within a single physical line. `install.ps1` assigns `$shortcutArgs` a hidden window at :3419 and overwrites it with a relaxed policy at :3433, fourteen lines apart in the same function, and that passed for as long as it existed. A scanner reads the file, not the line. Three layers now: 1. Same line, unchanged, because it gives the clearest message when it is the real shape. 2. A ratchet on how many relaxed policies the file contains at all, against `KNOWN_BYPASS_SITES`, which records each remaining site with the reason and what would remove it. It fails **both** ways: too many is a new site, too few is a stale entry that has quietly stopped guarding anything. This is the layer that catches a policy arriving somewhere the other two do not model. 3. Same variable, any distance: the union of everything assigned to one name must not contain both flags. This is the layer that sees the 3419/3433 shape. `install.ps1`'s `$shortcutArgs` is recorded in `KNOWN_SPLIT_PAIR_VARIABLES` rather than failed on. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, because `%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned refuses an unsigned script, and a shortcut that silently does nothing is worse than the token. Recording it lets the guard land now and lock in "no new ones", which is the part that matters going forward. ## Verification 70 passed in the suite, and each new layer was confirmed to bite rather than assumed to: - A new relaxed policy injected into `studio/setup.sh` fails layer 2, naming the file, line number, the offending line, and what to do about it. - Removing the recorded site from `studio/setup.bat` without lowering its count fails layer 2 the other way, telling the reader to lower the count in the same commit. - Layer 3 proved in isolation by renaming `$shortcutArgs` to `$launchArgs` in `install.ps1`: the relaxed-policy count is unchanged so layer 2 passes, and layer 3 fires on its own. The tree was restored after each and re-verified clean. `tests/studio/install/` and the shape suite are green; `test_pr10648_offline_and_status.py::test_the_pr_only_added_new_arms_to_the_setup_status_blocks` fails identically on `main` in a separate worktree and is untouched by this change. * Load the installer scripts under RemoteSigned instead of relaxing the policy Removes three of the four relaxed execution policies the ratchet in the previous commit recorded. RemoteSigned refuses an unsigned script only in the Internet or Untrusted zone, so for a local, unmarked script it behaves identically to Bypass while dropping a token endpoint products score. ## studio/setup.bat `powershell -ExecutionPolicy Bypass -File "%~dp0setup.ps1"` becomes RemoteSigned. setup.ps1 ships beside the batch file inside an installed package, so it is MyComputer-zone and loads unsigned either way. One population could regress: a package unzipped from a download, where setup.ps1 carries a mark of the web that RemoteSigned honours and Bypass ignored. So the mark is cleared first. Execution policy governs script *files* and not `-Command`, so that call runs under any machine policy, and clearing an absent stream writes nothing. The path travels in an environment variable rather than being interpolated into the command string, because an apostrophe in an install path is a real Windows user name and would otherwise break the quoting. `-NoProfile` is on the unblock call and deliberately **not** on the launch. The launch has always run setup.ps1 with profiles loaded, and `tests/studio/test_amd_venv_repair_loop.ps1` drives a profile that sets `Set-StrictMode -Version Latest` against it. Adding the flag would have retired that coverage with nothing failing, so the new test asserts its absence and says why. ## scripts/uninstall.ps1 and README.md Both print `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` as the documented way to run a cloned script. Changed to RemoteSigned rather than dropped: the Windows client default is `Restricted`, which blocks every script file including a local unsigned one, so the `Set-ExecutionPolicy` itself is load-bearing and removing it would break the documented path. RemoteSigned is sufficient because a git clone carries no mark of the web, and both now say so and point a zip user at `Unblock-File`, which is the case where the two policies genuinely differ. The uninstaller line is never executed -- it lives in the printed `_Usage` here-string -- but AMSI scans the file whole and a classifier cannot tell a string from a statement. ## Where that leaves the ratchet Four recorded sites down to one. The survivor is `install.ps1:3433`, the roaming-profile fallback for a launcher on a share, and it stays because `%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned would refuse the launcher, and a desktop shortcut that silently does nothing is worse than the token. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, which is a larger change than this one. ## Verification - 751 passed, 6 skipped across the shape suite, `tests/test_installer_interactive_prompts.py` and `tests/security/`. All of `tests/sh` passing. The parse gate clean over all three `.ps1` files. - Both new `setup.bat` assertions confirmed to bite: adding `-NoProfile` to the launch fails with the reason and names the test that would lose coverage, and reverting the policy to Bypass fails naming the offending line. The tree was restored after each. - Relaxed-policy sites counted directly across all seven shipped scripts afterwards: one, in install.ps1, as recorded. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Step setup.bat down to Bypass for a script on a share, the way install.ps1 already does Tightening setup.bat from Bypass to RemoteSigned had one case that is a genuine regression rather than a theoretical one, and it needed handling rather than accepting. Execution policy is judged on the script file's ZONE. A plain \\server\share and a mapped drive are Intranet and load fine under RemoteSigned -- but a dotted-FQDN UNC (\\corp.example.com\...), a DFS path or an IP-literal share is the Internet zone, where RemoteSigned refuses an unsigned script. And Unblock-File cannot save that case: with no Zone.Identifier stream present the PATH decides, so clearing a stream that was never there changes nothing and exits silently. Bypass worked; RemoteSigned does not. install.ps1:3405-3421 already solves exactly this when it writes the Start Menu shortcut -- UNC prefix, then DriveInfo.DriveType -eq 'Network' -- and the new test's own comment calls that site "the only one that is genuinely load-bearing" for the same reason. setup.bat got no such exemption. Now it reuses the identical logic rather than inventing a second answer. The probe does the Unblock-File too, so this costs one process rather than two, and it runs under -Command, which execution policy does not govern at all. Two details that matter more than they look: - The batch variable DEFAULTS to RemoteSigned. A probe that fails to run therefore leaves the tightened policy in place rather than silently restoring the relaxed one. - -NoProfile is on the probe and still deliberately absent from the launch. tests/studio/test_amd_venv_repair_loop.ps1 drives a profile that sets Set-StrictMode against setup.ps1, and adding it would retire that coverage with nothing failing. Tests: the embedded probe is extracted from the batch file and PARSED, because it is one long line inside a `for /f` backquote block and a syntax error there fails quietly -- the `for /f` captures nothing, the RemoteSigned default stands, and the mark is never cleared, so an unzipped download gets a refusal with no hint that the probe was what broke. The pre-existing setup.bat test located the launch by literal filename, which is now an environment variable, so it matches on the flags instead. 5713 passed, 39 skipped across tests/studio/test_installer_av_shapes.py, tests/studio/install/ and tests/security/. The single failure, test_pr10648_offline_and_status, is pre-existing on main. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Group the hidden/bypass pair by casefolded variable name PowerShell variable names are not case-sensitive, so $shortcutArgs and $ShortcutArgs are one variable. The same-variable layer keyed its map on the captured spelling, so writing the two assignments with different capitalisation filed them as two unrelated names, each holding only one of the two flags, and the pair went through. The file-wide ratchet did not catch it either, since install.ps1 already records one permitted relaxed policy. Verified by constructing that exact evasion: renaming the two install.ps1 assignments to $launchArgs and $LaunchArgs passes under the old grouping and fails under this one, naming both spellings. * Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them (#10990) * Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Match banned vendor tokens on word boundaries, and drop the one that cannot work The guard searched for each token as a raw substring, so it rejected ordinary installer prose: 'panda' is inside 'pandas', a real dependency name, and 'rising' is inside 'surprising', 'arising' and 'comprising'. The failure message then accuses a normal sentence of naming an antivirus vendor, and the fix the next reader reaches for is to delete the guard. Boundaries are conditional on the token's own edges, because 'heur:' and 'gen:variant' sit on a colon where \b asserts the opposite of what is wanted. 'rising' is removed rather than bounded. It is a real engine and one of the two that flagged the fixture archives, but the word is also ordinary English -- 'rising memory use' is a sentence someone will write -- and no amount of boundary matching separates the two. A guard that fails on valid prose is worth less than nothing. 'tencent', the other engine that flagged those archives, has no such problem and stays. Verified both directions against studio/setup.sh: a comment naming Bitdefender, Gen:Variant and Panda still produces three failures, while 'rising memory use' plus 'installs pandas' now passes and produced two misleading failures before. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the AppDomain fallback into the WSL emit, and quote TEMP inside cmd The generated script had only the static AssemblyBuilder spelling under a bare catch, so on any host lacking that overload both SHChangeNotify refreshes would stop with nothing printed. install.ps1 already tries both for this reason; mirror it. cmd expands a variable before it parses metacharacters, so an unquoted echo %TEMP% on a profile holding an ampersand, which is legal in a Windows account name, splits into two commands and the captured line is not the temp path. Quote it inside cmd and strip the quotes back off. The test stub now reproduces cmd's expand-then-parse order so the ordinary path still passes and only the ampersand case moves. * Keep the backend prewarm files as they are on main An all-files formatter pass reflowed two studio/backend files that have nothing to do with the WSL installer change and pulled them into this PR's diff. Restore them so the blast radius is only the installer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Strip cmd's quotes before trimming trailing blanks Trimming first found nothing to trim, because the closing quote was still the last character, so a Windows TEMP ending in spaces came back untrimmed and the directory check then cleared it. Win32 strips those spaces from a path and [ -d ] does not. The test stub was also wrong in a way that hid this: it consumed the quotes itself, but cmd's echo prints its argument verbatim, quotes included. With the stub corrected the new case fails against the previous commit and the rest still pass. * Fall through to a local Windows temp when TEMP is on a share A script written under a redirected %TEMP% is a remote script, and RemoteSigned refuses an unsigned one, so roaming-profile users would silently stop getting the shortcut they used to get. Rather than relax the policy back to Bypass, try %LOCALAPPDATA%\Temp and then %SystemRoot%\Temp, skipping any candidate that is UNC or still unexpanded. install.ps1 solves the same problem for the launcher by relaxing the policy because the launcher cannot move; this script can. * Reject mapped network drives as temporary locations too Z:\Temp is the same share and the same remote zone as its UNC spelling, and install.ps1 treats DriveType.Network as remote for that reason, but the filter only rejected paths beginning with two backslashes. A mapped drive was therefore accepted and then refused by RemoteSigned at launch. Read the mapped letters from net use and skip candidates on them; if that cannot be read the set is empty and only the UNC check applies, which is the previous behaviour rather than a new failure. * Keep shortcuts working when no Windows drive is mounted With [automount] enabled=false, interop still works but no Windows directory is reachable as a Linux path, so no candidate can be allocated and the file-based launch cannot run at all. Those users got a shortcut before the move off /tmp, so losing it silently is a regression rather than a pre-existing gap. The generated script is now captured once and either written to the Windows temp and run with -File, or handed to powershell on stdin. The stdin path needs no policy relaxation, because execution policy applies to -File and not to -Command, and nothing has to be mounted. It is fed from its own pipe so it cannot drink the installer's stdin under curl | sh. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Validate both halves of the compiler watch in the WSL control The control checked only the process half, so a FileSystemWatcher that never attached, or stopped reporting creations, looked exactly like a run that dropped no library. TempLibraries is the half the Bitdefender report in #10540 keyed on, and the install below trusts it. Require both, as windows-no-compiler-ci.yml already does. * Check the shell suite's failure counter after the last assertion The only $FAIL check sat before the static half of the file. `bad` records a failure and returns success, so an assertion that ran after it printed FAIL and left the script exiting 0, which made the launch-path regression checks ineffective in CI. Moved the summary and the check to the end of the file. * Do not render install.sh with a Windows bash The new here-string renderer drives install.sh through bash, and on a Windows runner bash is Git Bash or the WSL stub in System32, neither of which install.sh is ever run by: its WSL arm is gated on /proc/version naming microsoft, so the shell reading this here-string is always a POSIX one inside the distro. The rendered text is a pure function of install.sh's bytes, so the Linux and macOS legs cover the subject and the Windows leg only contributed three failures. Skipped there, the way the repository already skips its other bash-driven installer tests. Also report the shell's own diagnostic rather than letting CalledProcessError replace it with a 6 KB repr of the script. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…op discarding the false-positive submission packets (unslothai#10986) * Capture the evidence six reports of this never contained, and stop discarding the packets Every report of security software blocking Unsloth (unslothai#8523, unslothai#6326, unslothai#6588, unslothai#6648, unslothai#10540, unslothai#10805) named no antivirus product, no detection name and no AMSI provider. Clearance is per hash and vendors act on a detection name, so not one of those reports could be submitted anywhere, and not one of the six hardening passes since can be shown to have fixed what it aimed at. That is the gap here. ## A required-field issue form `.github/ISSUE_TEMPLATE/install-blocked-windows.yml`, a form rather than a markdown template for one reason: a form can mark a field `required` and a template cannot. Required: the product and version, the detection name exactly as displayed, the full error including the `FullyQualifiedErrorId` line, and the output of a collection script. Also a dropdown separating "the script would not run at all" from "something it created was blocked", because those are different mechanisms with different fixes and have been conflated in past reports. The script reads registered antivirus products from `root/SecurityCenter2`, resolves each AMSI provider CLSID through `InprocServer32` to a DLL and reads its `CompanyName`/`ProductName`/version, then `Get-MpComputerStatus` and recent Defender events. The provider resolution is the part that actually answers "which product", since a bare CLSID is not actionable. So is `AMRunningMode`: anything other than `Normal` means another product is primary. It downloads nothing, writes nothing, and changes nothing -- and it deliberately carries none of the shapes the installers are being cleaned of, because a diagnostic that trips the same product that blocked the installer is worthless. A test enforces that: no `Add-Type`, no `Invoke-Expression`, no base64, no `Set-MpPreference`, no `Remove-Item`, no `Start-Process`. ## The packets that were being thrown away Two false-positive submission packets are built today and discarded. `release-desktop.yml` writes a Microsoft submission packet to `$RUNNER_TEMP` and never uploads it, so `flagged-windows-bundles-*` held the flagged bundles and nothing describing them; it is now included in that artifact. And `scripts/virustotal_scan.py`'s packet went only into a job summary, which is ephemeral, so the one document written for the purpose of disputing a detection was discarded along with the run; it is now kept as an artifact. Retention on the flagged bundles goes from 7 days to 90. Clearance is per hash and a rebuild hashes differently, so those copies are the only submittable sample for that release, and a vendor round trip plus our own reaction routinely outlasts a week -- after which the evidence for the detection being disputed is gone. `test_the_scan_job_is_not_conditioned_away` allowed `if: always()` on exactly one step. The new upload needs it for the identical stated reason, "precisely so the evidence survives a failed scan", so the exception becomes a named set of two rather than a shape a future step could inherit by resembling. ## Verification - 675 passed, 6 skipped across `tests/security/` and `tests/python/test_virustotal_scan.py`. - The collection script is extracted from the YAML and **parsed**, not eyeballed. It is pasted verbatim by people who are already stuck, so a syntax error in it costs them a round trip and reports our form instead of their antivirus. It also runs end to end under pwsh on Linux, where every Windows-only facility reports itself unavailable and nothing crashes. - That guard earned itself immediately: the first draft put the script in a YAML **folded** scalar (`>`), which joins every line and silently collapsed the whole code block to nothing. The test catches that specific mistake and names it as the likely cause. - Both new guards confirmed to bite: reverting the scalar to `>` fails three tests, and making `detection-name` optional fails with the reason the field exists. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Upload the submission packet after the step that writes it, and make the form's labels real Two defects found reviewing this PR, both of which would have failed silently. ## The packet was uploaded sixty lines before it was written `Preserve flagged Windows bundles` is step 24; the packet is assembled in step 26. Steps run top to bottom, so `${{ runner.temp }}/ms-submission-packet.md` never existed when that upload ran -- and `if-no-files-found: ignore` would have hidden it permanently. The artefact meant to carry a vendor submission would have held the flagged bundles and nothing describing them, which is the exact failure this PR exists to fix, reintroduced one step higher up. The packet now has its own upload step immediately after the step that writes it. The path is removed from the earlier step rather than left in as harmless, because a path that cannot match is a claim the file is covered. Removing it also avoids a side effect worth knowing: upload-artifact computes the artefact root from glob pattern prefixes rather than matched files, so the second path would have re-rooted that zip from flat to nested. `if-no-files-found: ignore`, not `warn`: the packet is only assembled when there is something to submit, so its absence on a clean release is the normal case and must not add an annotation to every green run. ## Two of the form's three labels did not exist `windows` and `antivirus-false-positive` were not among the repository's labels. GitHub does not error on an unknown label, it drops it -- so every issue filed through this form would have arrived with `bug` only, losing precisely the two triage labels the form exists to attach, with nothing reporting the loss. Both labels now exist on the repository, and `test_the_labels_the_form_declares_are_real` keeps the form and the repository in step. It checks against a checked-in list rather than the GitHub API, because a test that needs the network is a test that gets skipped. * Start pwsh through the shared runner here too Same reason as the sibling fix in the AMSI probe lane: tests/studio/test_pwsh_calls_use_the_shared_runner.py bans a direct subprocess call to pwsh, because a direct one shares a single $XDG_CACHE_HOME/powershell startup cache with every xdist worker and an interpreter that dies at startup then reads as the script under test having failed. Caught only by running the full suite against all ten open PRs merged into one tree; the guard lives in tests/studio/ and never ran against this branch alone. * Redact the profile directory and account name before the report is published The collection block is a required field, so its output goes into a public issue, and it printed Path and Process Name for every Defender detection in the last two hours whether or not it had anything to do with Unsloth. On a normal machine those paths begin with the profile directory and therefore carry the account name, and the file name can be anything the person had open. The description also promised it touched no personal data, which was not true. Redact at the point of printing rather than asking the reporter to do it, since the reporter is someone whose install is already broken and who is pasting a block they did not write. Say plainly what is still printed and tell them to read it first. Verified against paths with a space in the name and with mismatched case. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Match the Defender event fields, which are indented Defender renders 1116 and its siblings as a header line followed by indented 'Field: value' lines, so anchoring on '^Name:' matched none of them and the section that exists to carry the detection name, the path and the triggering process emitted a timestamp and an event id and nothing else. Measured against a message in the documented shape: the old filter selects the empty string, the new one selects all six fields. Severity is included now too, since it is free once the line is being read and it is the field that tells us whether a report is a block or a warning. The guard drives the snippet's own filter rather than asserting the regex text, so a future rewrite is judged on what it extracts. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Give screenshots their own field, survive localised Defender labels, warn on the error field too A render: textarea wraps everything it contains in a code fence, attachments included, so the error field invited a screenshot it could never display. It keeps render: text, because it carries pasted console output where the monospace block earns its place, and screenshots get their own unrendered field. Defender localises the event field labels, so the English-only filter missed them and a non-English reporter would have sent a timestamp and an event id. Testing for an empty result is not enough: German renders Name: identically, so one match out of six looks like a successful extraction. The fallback counts instead, and prints the whole message, redacted and truncated, when fewer than two fields resolve. Measured on English, German and Japanese messages. The privacy note covered the probe output only. A PowerShell error quotes the script's location, so on the documented cloned-checkout path the required error field carries the reporter's user name and they are told to paste it verbatim before they reach that note. It now says the issue is public and suggests the substitution. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Warn on the issue form field that asks for a full path The error and probe fields say the issue is public and show what to write instead, but the file path field asked for a full path with only a profile-shaped placeholder to follow, so a reporter doing what it says publishes their user name. Give it the same warning and the same worked replacement. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Redact only real account components, and scope the probe's error preference The username replacement rewrote every case-insensitive occurrence anywhere in the line, so an account named win rewrote Windows Defender and one named cat rewrote Wacatac. Those are the product and detection names the form exists to collect, and the reporter cannot see it happen. Require a path separator before the name and no word character after it. The probe also set ErrorActionPreference at the prompt, which persists for the rest of that session, against the field's own promise that it changes nothing. Run the body in a script block so the assignment is scoped to it. * [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>
…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>
…hine (unslothai#10978) * WSL installer: stop running the C# compiler on the user's Windows machine `install.sh` generates a PowerShell script and runs it on the Windows side to create the WSL shortcut. Two constructs in that path were removed from `install.ps1` in earlier passes and left live here, where nothing looked: - `install.sh:2249` declared `SHChangeNotify` with `Add-Type -MemberDefinition`. On Windows PowerShell 5.1 that writes C# to `%TEMP%` and runs `csc.exe`, producing a DLL on the user's machine. unslothai#10540 traced exactly that chain to Bitdefender `Gen:Variant.MSILHeracles.272113`: `unsloth-stud... -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll`. It replaced the declaration in `install.ps1` with reflection emit and missed this copy. - `install.sh:2273` launched the generated script with `-ExecutionPolicy Bypass`, the flag unslothai#7822 removed everywhere else. Neither was caught because `test_the_installer_never_runs_the_c_sharp_compiler` parametrised over `("install.ps1", "studio/setup.ps1")` only, and `windows-no-compiler-ci.yml` did not list `install.sh` in its path triggers. A shell script that emits PowerShell can put a compiler on a Windows machine without touching a `.ps1`. ## The compile `SHChangeNotify` is now emitted, mirroring `install.ps1:3485-3499`: a `DefineDynamicAssembly` / `DefineDynamicModule` / `DefineType` / `DefinePInvokeMethod` / `CreateType` block inlined, since the generated script is standalone and cannot call `New-StudioEmittedNativeType`. The enclosing `try {} catch {}` stays, so a failure still costs only a stale icon, and both notifications stay: per-item `SHCNE_UPDATEITEM` + `SHCNF_PATHW` per `.lnk`, then the global `SHCNE_ASSOCCHANGED`. The per-item call is not redundant, and the `ALLOWED_PINVOKES` entry records why: `ie4uinit.exe -show` does not recover a stale same-name `.lnk`. I ran the emitted type rather than assuming it: under pwsh it produces `void SHChangeNotify(Int32, UInt32, String, IntPtr)`, identical to the `Add-Type` declaration, `PreserveSig` set, and `Assembly.Location` empty, which is the point. Nothing reaches disk. ## The execution policy `Bypass` was load-bearing, for one reason: `wslpath -w /tmp/unsloth-shortcut-XXXXXX.ps1` yields a `\\wsl.localhost\<distro>\...` UNC path, PowerShell treats a script there as remote, and `RemoteSigned` refuses an unsigned remote script. So rather than relax the policy, the script now goes to the Windows `%TEMP%` (`cmd.exe /c echo %TEMP%`, CR stripped, `wslpath -u`), which is a local volume and therefore `MyComputer` zone, where `RemoteSigned` loads it unsigned. Same generated script, same launch, same result. When `%TEMP%` cannot be resolved there is deliberately **no fallback to WSL's `/tmp`**, because that is the case that needed the relaxed policy in the first place. Nothing is allocated and the caller takes the notice it already prints when interop is unavailable. That population is very nearly the population where interop is already broken. ## Tripwires, with messages that say what is wrong `tests/sh/test_wsl_shortcut_script_location.sh` evals the real resolution block out of `install.sh` with `cmd.exe` and `wslpath` stubbed, covering resolved, no-interop, unexpanded `%TEMP%`, and a `%TEMP%` that is not a directory, then asserts statically that the launch uses `RemoteSigned`, that the file relaxes the policy nowhere, that it compiles no C#, and that both refreshes survive. A failed extraction is reported as a failure rather than exiting early, so the output names every problem at once, and it still fails closed. `clean-machine-install-ci.yml`'s `wsl` job is the only lane that runs this branch, so it gains the behavioural half: read the created `.lnk` back and refuse a script-host target, require the generated script to have been cleaned up, and fail on any `.cmdline`/`.rsp` under the Windows `%TEMP%`, which is csc.exe output and nothing else. That check plants two intermediates and requires the search to find both before trusting a negative result, because a detector that sees nothing looks exactly like a clean run and every reason it might see nothing is silent. If the control does not fire the job fails as a broken detector instead of reporting a pass. Shortcut absence is a warning, not an error, since the installer itself treats shortcut creation as best-effort. `install.sh` is added to the compiler test's parametrise list and to `windows-no-compiler-ci.yml`'s paths. The `DefinePInvokeMethod` assertion in that test becomes conditional on the file declaring a native import at all, so it does not fail for being satisfied on `scripts/uninstall.ps1` or `studio/setup.sh`. ## Verification - The new shell suite: 16 passed on this branch, and against `main` in a worktree it exits 1 with 6 named failures. Proved to bite rather than assumed to. - The generated WSL script rendered and parsed with `[System.Management.Automation.Language.Parser]::ParseFile`: clean over 765 tokens. No existing gate parses that here-string, and this change edits it. - `bash -n` and `sh -n` on `install.sh`; all of `tests/sh` passing; the parse gate clean over `install.ps1`, `studio/setup.ps1` and `scripts/uninstall.ps1`. - `tests/studio/test_installer_av_shapes.py`, `tests/studio/install/`, `tests/security/`: green. - The new CI PowerShell parsed standalone, and its positive control plus detector exercised for real against a planted `csc.exe`-style intermediate: control 2 of 2, simulated compile caught, clean directory reports zero. I have no Windows or WSL here, so the runtime behaviour of the shortcut path rests on the `clean-machine-install-ci.yml` WSL job, not on a local run. This is a shape fix with a confirmed detection behind the shape; it is not a claim that any particular user report is resolved. * Fix a test of mine that passed for the wrong reason, and could only fail on a real CI machine `test_wsl_shortcut_script_location.sh` asserted that the generated shortcut script's path does not start with `/tmp`, as a proxy for "not in WSL's own temp, which wslpath turns into a \\wsl.localhost UNC path that RemoteSigned refuses". The proxy is broken: the harness builds its *fake Windows temp* with `mktemp -d`, so on any machine with `TMPDIR=/tmp` -- which is every normal CI runner -- the stub's own directory matched the pattern and the test failed while install.sh was behaving exactly as intended. It passed locally only because this workspace sets `TMPDIR` elsewhere. That is precisely the class of accidental pass the rest of this work has been built to catch, so it is worth naming rather than quietly correcting. The replacement asserts the property the proxy was standing in for, structurally: the block contains exactly one `mktemp`, so there is no second path to fall back to, and that `mktemp` allocates inside `$_css_win_temp`. Both are true or false regardless of where anyone's temp directory happens to live. Verified under the exact condition that broke it: `TMPDIR=/tmp` gives 17 passed, 0 failed on this branch, and 6 failed on `main` in a clean worktree -- so the test still bites. * WSL installer: read %TEMP% with cmd /d, so an AutoRun command cannot cost the user their shortcut Reading the Windows %TEMP% through interop is new in this branch, and it reads it with `cmd.exe /c echo %TEMP%`. Without /d, cmd first runs the AutoRun command from HKLM or HKCU \Software\Microsoft\Command Processor, and `cmd /c` is not exempt from that. AutoRun writes to the same stdout, so its output arrives ahead of the path and `tr -d '\r\n'` glues the two into one string. wslpath then rejects it, the directory check fails, and the branch takes its "couldn't create the Windows shortcut" notice. Clink sets an AutoRun, so Cmder does, and so do plenty of corporate images. Every one of those users got a working shortcut before this branch and would silently stop getting one, while being told WSL interop is disabled, which is not what happened. So: /d, which is the cheap fix rather than out-parsing whatever prints. Then the last line rather than the whole stream, for anything that still reaches stdout by another route, and trailing blanks trimmed, because Win32 strips them from a path and [ -d ] does not, so a %TEMP% set with one resolved to a directory that appeared not to exist. The || stays: this file runs under set -e, where a failed substitution ends the install. Tests ----- tests/sh/test_wsl_shortcut_script_location.sh grows the AutoRun and trailing-blank cases and a static check for /d, and its wslpath stub is now input-sensitive. It was not, and that mattered: a stub that returns the fake Windows temp whatever it is handed cannot tell "install.sh read the path" from "install.sh read a banner glued to a path", so both new cases passed against the unfixed file until the stub compared its argument. Against the unfixed install.sh the four new assertions fail; with it they pass. tests/studio/test_wsl_shortcut_script_is_valid_powershell.py is new and covers a gap nothing else did: that what install.sh generates is PowerShell at all. bash -n sees the here-string as a here-string, the contents only run on Windows with both streams sent to /dev/null, and the icon-refresh block runs inside try/catch, so a parse error there is not a crash and not a message, just no shortcut and a misleading notice. The block was just rewritten into a twenty-line reflection-emit sequence, which is when that matters most. The file renders the here-string with a real shell rather than keeping a copy, parses it, and then executes the emit sequence retargeted at a symbol this host exports, so a wrong call order or argument count fails on Linux. Five mutations of the shipped file were tried; four fail it, and the docstring names the fifth that does not and why. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Watch the WSL install live, instead of searching for what CodeDom already deleted The lane looked for .cmdline and .rsp files in the Windows temp after the install had finished. CodeDom removes its whole intermediate directory once the assembly is loaded, which Watch-ForCompiler.ps1 records as a before-and-after diff seeing nothing at all while 4688 recorded csc.exe, so that search could not fail for the case this lane exists to catch. Its positive control planted persistent files, which proves the search can traverse a directory and nothing about whether ephemeral compiler output is observable. The install now runs inside Invoke-WithCompilerWatch, the same detector windows-no-compiler-ci.yml uses, which unions 4688 with a live FileSystemWatcher and treats an unreadable Security log as void rather than clean. The dropped-library half is checked too, since that is what the Bitdefender report in unslothai#10540 keyed on. The post-hoc listing stays for what genuinely is left behind, which is the other half of the union, and its message now says that is what it means. Watch-ForCompiler.ps1 is in both path filters now, because this job's detection depends on it, and the new guard is registered in the unfiltered lint job since it reads a workflow file. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Arm the 4688 half of the compiler watch in the WSL lane Watch-ForCompiler.ps1 requires the caller to enable process creation auditing, and this job never did, so its Security log query returned an empty compiler list whatever ran while the step still printed that no compiler process was seen. Enable and verify the audit policy before the install, and require a deliberate compile to be detected first, so a clean verdict is distinguishable from a detector that never attached. * Close the AV shape-guard holes, and load the installers under RemoteSigned (unslothai#10982) * AV shape guards: watch the two shipped scripts nothing watched, and ratchet the policy sites Stacked on the WSL compiler fix, which shares this file. Two problems, both found while investigating unslothai#10805, and both about the guard rather than the code it guards. ## Two shipped scripts were in no list `PS_SCRIPTS` and `SH_SCRIPTS` between them missed `studio/setup.bat` and `scripts/uninstall.sh`. A shipped `.bat` is scanned like any other file, and `setup.bat` launches PowerShell, so every rule here applies to it. That is how its `-ExecutionPolicy Bypass` survived the passes in unslothai#7822 and unslothai#8586: the guards were reading a set of files that did not include it. Both are added to `ALL_SCRIPTS`. ## The hidden-window pair check only ever looked at one line `test_a_hidden_window_never_pairs_with_a_bypassed_policy` iterated `splitlines()` and compared the two flags within a single physical line. `install.ps1` assigns `$shortcutArgs` a hidden window at :3419 and overwrites it with a relaxed policy at :3433, fourteen lines apart in the same function, and that passed for as long as it existed. A scanner reads the file, not the line. Three layers now: 1. Same line, unchanged, because it gives the clearest message when it is the real shape. 2. A ratchet on how many relaxed policies the file contains at all, against `KNOWN_BYPASS_SITES`, which records each remaining site with the reason and what would remove it. It fails **both** ways: too many is a new site, too few is a stale entry that has quietly stopped guarding anything. This is the layer that catches a policy arriving somewhere the other two do not model. 3. Same variable, any distance: the union of everything assigned to one name must not contain both flags. This is the layer that sees the 3419/3433 shape. `install.ps1`'s `$shortcutArgs` is recorded in `KNOWN_SPLIT_PAIR_VARIABLES` rather than failed on. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, because `%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned refuses an unsigned script, and a shortcut that silently does nothing is worse than the token. Recording it lets the guard land now and lock in "no new ones", which is the part that matters going forward. ## Verification 70 passed in the suite, and each new layer was confirmed to bite rather than assumed to: - A new relaxed policy injected into `studio/setup.sh` fails layer 2, naming the file, line number, the offending line, and what to do about it. - Removing the recorded site from `studio/setup.bat` without lowering its count fails layer 2 the other way, telling the reader to lower the count in the same commit. - Layer 3 proved in isolation by renaming `$shortcutArgs` to `$launchArgs` in `install.ps1`: the relaxed-policy count is unchanged so layer 2 passes, and layer 3 fires on its own. The tree was restored after each and re-verified clean. `tests/studio/install/` and the shape suite are green; `test_pr10648_offline_and_status.py::test_the_pr_only_added_new_arms_to_the_setup_status_blocks` fails identically on `main` in a separate worktree and is untouched by this change. * Load the installer scripts under RemoteSigned instead of relaxing the policy Removes three of the four relaxed execution policies the ratchet in the previous commit recorded. RemoteSigned refuses an unsigned script only in the Internet or Untrusted zone, so for a local, unmarked script it behaves identically to Bypass while dropping a token endpoint products score. ## studio/setup.bat `powershell -ExecutionPolicy Bypass -File "%~dp0setup.ps1"` becomes RemoteSigned. setup.ps1 ships beside the batch file inside an installed package, so it is MyComputer-zone and loads unsigned either way. One population could regress: a package unzipped from a download, where setup.ps1 carries a mark of the web that RemoteSigned honours and Bypass ignored. So the mark is cleared first. Execution policy governs script *files* and not `-Command`, so that call runs under any machine policy, and clearing an absent stream writes nothing. The path travels in an environment variable rather than being interpolated into the command string, because an apostrophe in an install path is a real Windows user name and would otherwise break the quoting. `-NoProfile` is on the unblock call and deliberately **not** on the launch. The launch has always run setup.ps1 with profiles loaded, and `tests/studio/test_amd_venv_repair_loop.ps1` drives a profile that sets `Set-StrictMode -Version Latest` against it. Adding the flag would have retired that coverage with nothing failing, so the new test asserts its absence and says why. ## scripts/uninstall.ps1 and README.md Both print `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` as the documented way to run a cloned script. Changed to RemoteSigned rather than dropped: the Windows client default is `Restricted`, which blocks every script file including a local unsigned one, so the `Set-ExecutionPolicy` itself is load-bearing and removing it would break the documented path. RemoteSigned is sufficient because a git clone carries no mark of the web, and both now say so and point a zip user at `Unblock-File`, which is the case where the two policies genuinely differ. The uninstaller line is never executed -- it lives in the printed `_Usage` here-string -- but AMSI scans the file whole and a classifier cannot tell a string from a statement. ## Where that leaves the ratchet Four recorded sites down to one. The survivor is `install.ps1:3433`, the roaming-profile fallback for a launcher on a share, and it stays because `%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned would refuse the launcher, and a desktop shortcut that silently does nothing is worse than the token. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, which is a larger change than this one. ## Verification - 751 passed, 6 skipped across the shape suite, `tests/test_installer_interactive_prompts.py` and `tests/security/`. All of `tests/sh` passing. The parse gate clean over all three `.ps1` files. - Both new `setup.bat` assertions confirmed to bite: adding `-NoProfile` to the launch fails with the reason and names the test that would lose coverage, and reverting the policy to Bypass fails naming the offending line. The tree was restored after each. - Relaxed-policy sites counted directly across all seven shipped scripts afterwards: one, in install.ps1, as recorded. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Step setup.bat down to Bypass for a script on a share, the way install.ps1 already does Tightening setup.bat from Bypass to RemoteSigned had one case that is a genuine regression rather than a theoretical one, and it needed handling rather than accepting. Execution policy is judged on the script file's ZONE. A plain \\server\share and a mapped drive are Intranet and load fine under RemoteSigned -- but a dotted-FQDN UNC (\\corp.example.com\...), a DFS path or an IP-literal share is the Internet zone, where RemoteSigned refuses an unsigned script. And Unblock-File cannot save that case: with no Zone.Identifier stream present the PATH decides, so clearing a stream that was never there changes nothing and exits silently. Bypass worked; RemoteSigned does not. install.ps1:3405-3421 already solves exactly this when it writes the Start Menu shortcut -- UNC prefix, then DriveInfo.DriveType -eq 'Network' -- and the new test's own comment calls that site "the only one that is genuinely load-bearing" for the same reason. setup.bat got no such exemption. Now it reuses the identical logic rather than inventing a second answer. The probe does the Unblock-File too, so this costs one process rather than two, and it runs under -Command, which execution policy does not govern at all. Two details that matter more than they look: - The batch variable DEFAULTS to RemoteSigned. A probe that fails to run therefore leaves the tightened policy in place rather than silently restoring the relaxed one. - -NoProfile is on the probe and still deliberately absent from the launch. tests/studio/test_amd_venv_repair_loop.ps1 drives a profile that sets Set-StrictMode against setup.ps1, and adding it would retire that coverage with nothing failing. Tests: the embedded probe is extracted from the batch file and PARSED, because it is one long line inside a `for /f` backquote block and a syntax error there fails quietly -- the `for /f` captures nothing, the RemoteSigned default stands, and the mark is never cleared, so an unzipped download gets a refusal with no hint that the probe was what broke. The pre-existing setup.bat test located the launch by literal filename, which is now an environment variable, so it matches on the flags instead. 5713 passed, 39 skipped across tests/studio/test_installer_av_shapes.py, tests/studio/install/ and tests/security/. The single failure, test_pr10648_offline_and_status, is pre-existing on main. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Group the hidden/bypass pair by casefolded variable name PowerShell variable names are not case-sensitive, so $shortcutArgs and $ShortcutArgs are one variable. The same-variable layer keyed its map on the captured spelling, so writing the two assignments with different capitalisation filed them as two unrelated names, each holding only one of the two flags, and the pair went through. The file-wide ratchet did not catch it either, since install.ps1 already records one permitted relaxed policy. Verified by constructing that exact evasion: renaming the two install.ps1 assignments to $launchArgs and $LaunchArgs passes under the old grouping and fails under this one, naming both spellings. * Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them (unslothai#10990) * Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them PowerShell hands the entire top-level script block to AMSI at compile time, before the first statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's analysis of the file quoted one of our own comments back as grounds for suspicion: "The presence of comments that suggest the script is designed to evade detection by security tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the suspicion." Six hardening passes wrote careful explanations of which product flagged which shape directly into the files being scanned. The explanations are worth keeping. Their location is not. - A comment in a shipped script says **what the code does and what breaks if you change it**. - `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged which shape, and when**. The record lives in that test rather than a doc because the file already owns the guards that enforce the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains no non-comment line, which is checked mechanically rather than asserted. The record is not a dumping ground. It holds the measured detections (Skyhigh `BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the csc.exe output in unslothai#10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two fixture archives that made Panda flag the repo zip), the measured before-and-after from `virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing, and how to report a new detection. Three things a future pass will otherwise rediscover are written down there, because each one already cost a wrong proposal: execution policy is evaluated against the script file's zone and not against who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client default is `Restricted`, so documentation telling a user to set a process-scoped policy is load-bearing and only the word `Bypass` needed to go. A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there are three: - `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat` and `scripts/uninstall.sh`, which no shape test read before. - `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific detection strings -- a record with headings and no evidence is the same loss with extra steps. - `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to "security software blocks this" with no forward reference is worse than the prose it replaced: the next maintainer cannot tell whether it is still true. Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real runtime hazard the code handles and one of them reaches the user. Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false positive in a registry probe and has nothing to do with a scanner. A token list is only as good as its words having one meaning, and that one does not. - 14 of the new assertions fail against `main` and none against this branch, so they are proved to bite rather than to pass vacuously. - No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are not comments returns empty). - `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files. - Existing tests and CI that reference the old detection strings are unaffected: they live in `tests/` and `.github/`, which ship to nobody and are scanned by nothing. - One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the "must not still point at the doc" assertion into asserting the opposite. The stale path is now assembled from fragments so a future rename cannot do it again. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Match banned vendor tokens on word boundaries, and drop the one that cannot work The guard searched for each token as a raw substring, so it rejected ordinary installer prose: 'panda' is inside 'pandas', a real dependency name, and 'rising' is inside 'surprising', 'arising' and 'comprising'. The failure message then accuses a normal sentence of naming an antivirus vendor, and the fix the next reader reaches for is to delete the guard. Boundaries are conditional on the token's own edges, because 'heur:' and 'gen:variant' sit on a colon where \b asserts the opposite of what is wanted. 'rising' is removed rather than bounded. It is a real engine and one of the two that flagged the fixture archives, but the word is also ordinary English -- 'rising memory use' is a sentence someone will write -- and no amount of boundary matching separates the two. A guard that fails on valid prose is worth less than nothing. 'tencent', the other engine that flagged those archives, has no such problem and stays. Verified both directions against studio/setup.sh: a comment naming Bitdefender, Gen:Variant and Panda still produces three failures, while 'rising memory use' plus 'installs pandas' now passes and produced two misleading failures before. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the AppDomain fallback into the WSL emit, and quote TEMP inside cmd The generated script had only the static AssemblyBuilder spelling under a bare catch, so on any host lacking that overload both SHChangeNotify refreshes would stop with nothing printed. install.ps1 already tries both for this reason; mirror it. cmd expands a variable before it parses metacharacters, so an unquoted echo %TEMP% on a profile holding an ampersand, which is legal in a Windows account name, splits into two commands and the captured line is not the temp path. Quote it inside cmd and strip the quotes back off. The test stub now reproduces cmd's expand-then-parse order so the ordinary path still passes and only the ampersand case moves. * Keep the backend prewarm files as they are on main An all-files formatter pass reflowed two studio/backend files that have nothing to do with the WSL installer change and pulled them into this PR's diff. Restore them so the blast radius is only the installer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Strip cmd's quotes before trimming trailing blanks Trimming first found nothing to trim, because the closing quote was still the last character, so a Windows TEMP ending in spaces came back untrimmed and the directory check then cleared it. Win32 strips those spaces from a path and [ -d ] does not. The test stub was also wrong in a way that hid this: it consumed the quotes itself, but cmd's echo prints its argument verbatim, quotes included. With the stub corrected the new case fails against the previous commit and the rest still pass. * Fall through to a local Windows temp when TEMP is on a share A script written under a redirected %TEMP% is a remote script, and RemoteSigned refuses an unsigned one, so roaming-profile users would silently stop getting the shortcut they used to get. Rather than relax the policy back to Bypass, try %LOCALAPPDATA%\Temp and then %SystemRoot%\Temp, skipping any candidate that is UNC or still unexpanded. install.ps1 solves the same problem for the launcher by relaxing the policy because the launcher cannot move; this script can. * Reject mapped network drives as temporary locations too Z:\Temp is the same share and the same remote zone as its UNC spelling, and install.ps1 treats DriveType.Network as remote for that reason, but the filter only rejected paths beginning with two backslashes. A mapped drive was therefore accepted and then refused by RemoteSigned at launch. Read the mapped letters from net use and skip candidates on them; if that cannot be read the set is empty and only the UNC check applies, which is the previous behaviour rather than a new failure. * Keep shortcuts working when no Windows drive is mounted With [automount] enabled=false, interop still works but no Windows directory is reachable as a Linux path, so no candidate can be allocated and the file-based launch cannot run at all. Those users got a shortcut before the move off /tmp, so losing it silently is a regression rather than a pre-existing gap. The generated script is now captured once and either written to the Windows temp and run with -File, or handed to powershell on stdin. The stdin path needs no policy relaxation, because execution policy applies to -File and not to -Command, and nothing has to be mounted. It is fed from its own pipe so it cannot drink the installer's stdin under curl | sh. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Validate both halves of the compiler watch in the WSL control The control checked only the process half, so a FileSystemWatcher that never attached, or stopped reporting creations, looked exactly like a run that dropped no library. TempLibraries is the half the Bitdefender report in unslothai#10540 keyed on, and the install below trusts it. Require both, as windows-no-compiler-ci.yml already does. * Check the shell suite's failure counter after the last assertion The only $FAIL check sat before the static half of the file. `bad` records a failure and returns success, so an assertion that ran after it printed FAIL and left the script exiting 0, which made the launch-path regression checks ineffective in CI. Moved the summary and the check to the end of the file. * Do not render install.sh with a Windows bash The new here-string renderer drives install.sh through bash, and on a Windows runner bash is Git Bash or the WSL stub in System32, neither of which install.sh is ever run by: its WSL arm is gated on /proc/version naming microsoft, so the shell reading this here-string is always a POSIX one inside the distro. The rendered text is a pure function of install.sh's bytes, so the Linux and macOS legs cover the subject and the Windows leg only contributed three failures. Skipped there, the way the repository already skips its other bash-driven installer tests. Also report the shell's own diagnostic rather than letting CalledProcessError replace it with a 6 KB repr of the script. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
What is happening
Bitdefender blocks Unsloth Desktop on Windows 11 during the first "Get started" run, and running as administrator does not help. The reported chain is:
with the verdict
Gen:Variant.MSILHeracles.272113on the generated DLL. That DLL is produced on the user's machine at install time. It is in no release artifact.Two things narrow this down:
irm https://unsloth.ai/install.ps1 | iexworks on the same machine. Only the desktop app path is blocked, andtauri.windows.conf.jsonbundlesinstall.ps1into the exe, so the desktop app is what launches the interpreter that launches the compiler.v0.1.800-betainstalls fine,v0.1.803-betaand everything after blocks. Every release in that range is 0/70 on VirusTotal. So the shipped bytes are not what is being detected.What changed in that window is that the installer went from one
Add-Typecompile to two: #9178 added a retry that redirectsTEMPto a private directory and compiles again after the first attempt fails.Why the compile exists at all
Add-Type -TypeDefinitionon Windows PowerShell 5.1 has no in-process compiler. It writes a C# source file into%TEMP%, shells out tocsc.exe, and loads the resulting DLL. PowerShell spawning a compiler that writes executable code into%TEMP%is a generic malware pattern, and behavioural heuristics fire on it regardless of what the code does.The only thing the installer wanted from that compile was a handful of kernel32 and shell32 declarations.
The change
Reflection.Emitbuilds exactly those declarations in memory, so no compiler process runs, no source file is written and no DLL lands in%TEMP%.DefineDynamicAssemblyis available on .NET Framework 4 and on .NET 5+, so PowerShell 5.1 and PowerShell 7 take the same path.Four emitted types replace four compiles: the path resolver (
CreateFileW,GetFinalPathNameByHandleW,CloseHandle), the process-image lookup (OpenProcess,QueryFullProcessImageNameW,CloseHandle), the console thunk in both scripts (GetStdHandle,GetConsoleMode,SetConsoleMode) and the shell icon refresh (SHChangeNotify). The private-TEMPretry is gone with the compiler it existed for.install.ps1andstudio/setup.ps1now contain zeroAdd-Type -TypeDefinitionsites.Emitted and compiled declarations were compared member by member. Library, entry point, calling convention,
PreserveSig, return marshalling and parameter marshalling all match, including bothStringBuilderbuffers and theref uintwriteback. Two differences are real and stated rather than glossed:CharSetis declared per import. It selects which export the runtime probes first, andCloseHandle,OpenProcessand the three console calls wereCharSet.Nonein the C#, so they are declaredAnsiand the restUnicode, exactly as before.DefinePInvokeMethodcannot requestSetLastError, so every emitted import has it false. No caller readsGetLastWin32Error,GetLastPInvokeErrororGetLastError: the compiled version threw a codedWin32Exceptionthat its callers turned back into "use the lexical answer", and the replacement returns$null, which they treat identically. All ten call sites were checked individually.GetConsoleMode's second parameter wasout uintand a by-ref type alone emitsref, so the emitter callsDefineParameterto keep the metadata honest.When emit is not allowed
App Control's option 19, Dynamic Code Security, always blocks loading unsigned
System.Reflection.Emitassemblies, has no audit mode on Windows 10 or Windows 11 before 24H2, and Microsoft documents a blocked dynamic load as usually stopping or crashing the parent process. Nocatchrecovers that.Win32_DeviceGuardreports the enforcement state but not the option bit, so guessing costs one population or the other. Refusing every machine with an active policy would send Smart App Control users down the lexical path, and those are the same consumer desktops the report came from: SAC setsEnabled:UMCI, so the status is non-zero, but it does not set option 19 and does not force Constrained Language.So the machine is asked instead of guessed. With no policy active, which is nearly every machine, the answer is yes and nothing extra runs. With a policy active, a child PowerShell attempts the same emit and reports back; a block stops the child, which is the point of asking there.
The child's answer has three outcomes, not two. A child that ran and refused, by exiting non-zero or reporting a language mode its parent is not in, is a machine that cannot emit. A child that could not be spawned, was killed at the twenty second deadline, or produced no marker established nothing, and that case is retried once, the way the compiled version tried twice before caching a negative. Without the split, one transient process failure is cached for the whole run and is indistinguishable from a policy: the installer degrades, two unequal roots then compare as unknown rather than different, both the SID lock and the path lock are taken, and an unrelated install elsewhere on the machine surfaces as "The managed Unsloth environment is busy". The degradation warning names user-mode code integrity only for a child that actually refused, since naming a machine setting for a process that failed sends whoever reads that log looking for something that is not there.
That probe body is written with single quotes only, and that is load-bearing. Windows PowerShell 5.1 binds a native argument by wrapping it in double quotes and appending the body verbatim without escaping the double quotes inside it, so a body containing one is truncated and the child silently answers no. Reproduced by putting pwsh into that binder with
$PSNativeCommandArgumentPassing: the same probe answers False underLegacyand True underStandard. Base64 also fixes it and is what the documentation suggests, but base64 PowerShell is the shape this change exists to stop resembling, andtests/studio/test_installer_av_shapes.pyrejects it.Behaviour
On a machine where the native call works, nothing changes: same exact path, same
-Exact $true, same runtime lock decision. On a machine where it does not, the caller already handled$nulland failed closed, and still does.Two smaller corrections in the same area: the native handle is now acquired inside the
try/finallythat closes it, since anIntPtrhas no finalizer to fall back on where aSafeFileHandledid, and the initializers re-check whetherCreateTypepublished the type before caching a negative, which the compiled version did and the first draft of this dropped.A type this session already emitted outranks any probe, and every caller checks for one before consulting the gate. The compiled version could not disagree with itself here because a single type carried the path helper and the process-image helper; two types can, and the way they do is a session that emitted one, was interrupted, and came back to a probe that now fails, keeping native path resolution while silently losing process inspection. The console helper and the shell-icon refresh had the same ordering problem, where one failed probe discarded a helper already loaded and working in the same process.
The Device Guard query is bounded at ten seconds. What that bound covers is worth stating exactly:
-OperationTimeoutSeclimits the CIM operation on a responsive target, does not interrupt DCOM connection setup, and does not override a wedged provider, where the server's own timeout wins. It is worth having for the slow case and it is not a hang guard. The installer already queries CIM for adapters and processes, so this is not a new dependency.Evidence
Cross-OS, all green: windows-x64, windows-arm64, ubuntu-x64, ubuntu-arm64, macos-arm64, macos-intel, Ubuntu under WSL on a Windows host, and the macOS MLX branch. The Windows legs are the ones under test; the rest are the control for "a change confined to Windows disturbed nobody else".
Lock identity, measured on real Windows rather than argued. The concern is that a run resolving natively and a run falling back to the lexical resolver could hash the same directory differently and take different install locks. With the two rungs proven distinct in the log, the install mutex name is identical for a plain path, an 8.3 short name and a SUBST drive, on x64 and arm64.
A volume reached by its GUID rather than its drive letter does hash differently between the two rungs. That is a property of
GetFinalPathNameByHandleWversusGetFullPathand is unchanged here:Get-StudioLexicalPath,Get-StudioPathHash,Resolve-StudioFinalPathInfo,Get-StudioFinalPath,Get-StudioSubstTargetandGet-StudioInstallMutexNameare all byte-identical to main in this diff. The staging matrix runs the same measurement against main's copy as the control.Full test differential, whole suite, base against head: identical failure sets, no test that fails only on head.
Tests
tests/studio/test_native_path_resolver_degrades.ps1extracts the real resolver functions and runs them underpwshon POSIX, where emit succeeds andkernel32does not resolve, which is the build side and the call side in one run. It runs on the Linux leg ofcross-platform-parity-ci.yml, which is the host it describes, and exits early on Windows where every one of its assertions would be false..github/workflows/windows-no-compiler-ci.ymlis the behavioural half: it turns on 4688 process-creation auditing with command lines, runs the real installer in both shell and desktop mode, and fails ifcsc.exe,vbc.exeorcvtres.exeever appears or a DLL lands in a temporary directory. Its positive control runs first and deliberately compiles one throwaway type, requiring both detectors to fire, because a detector that sees nothing reads exactly like a clean run. The detector reads the image from the 4688 record's ownNewProcessNamefield rather than searching the rendered message, which contains the command line and scoredcmd.exe /c echo csc.exeas a compile; and a Security log it cannot read now fails the run as void instead of reporting it as clean.Which revision of
studio/setup.ps1each leg measures is part of the claim. The installer delegates setup to the managed CLI, so a default run executes the copy inside the released package, not the one in the checkout. The shell leg is therefore a measurement of the release; the desktop leg passes--local, which overlays the checkout as an editable install, refuses to report a result unless the overlay appears in the log, and records the measured path and hash. It also refuses to grade a run that never reached any install work.tests/studio/test_installer_av_shapes.pyreads imports declared throughDefinePInvokeMethod, asserts no C# compiler is invoked and no base64 payload is passed, and keeps asserting the lexical fallback is reachable.What this does not fix
This addresses the behavioural detection only. The llama.cpp payload fetched after install is unsigned and unknown to VirusTotal, which is a separate exposure to Smart App Control and is not touched here.
One limitation of the probe itself, stated because it is a design choice rather than an oversight. An App Control policy can approve a script FILE, so the installer runs in FullLanguage, while untrusted command text stays constrained. The child receives the probe as command text and does not carry the parent file's approval, so on such a machine it reports a constrained language mode and the installer degrades to the lexical resolver even though the parent could have emitted. That is the safe direction, and the alternative, writing a script file into a temporary directory to run it, is the exact shape this change removes.