Skip to content

Ask AMSI whether the installer compiles, which is the mechanism #10805 actually reports - #10994

Merged
danielhanchen merged 36 commits into
mainfrom
av-fp-amsi-defender-lane
Sep 15, 2026
Merged

danielhanchen merged 36 commits into
mainfrom
av-fp-amsi-defender-lane

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The reporter in #10805 was not running install.ps1 and watching it misbehave. The script was refused before its first statement ran, because PowerShell hands a script block to AMSI at compile time. Not one of the six hardening passes since has measured that, so none can be shown to have fixed it.

[scriptblock]::Create on the file's text reproduces that exact path with none of an install's side effects: no download, no venv, no registry, no shortcut. Nothing is invoked, only compiled, which is what makes running it on every candidate cheap and safe, unlike the two-full-installs lane in #10992.

Under Windows PowerShell 5.1 specifically. That is what install.rs spawns (install.rs:433-440), what a clean Windows box ships, and what the reporter ran; pwsh 7 is a different host with a different AMSI integration, so its answer does not transfer. RemoteSigned, not a relaxed policy: using Bypass in the lane built to remove Bypass would be absurd.

The second half scans the same files with Defender's on-demand scanner, each copy stamped with Zone.Identifier ZoneId=3 first so block-at-first-sight consults the cloud rather than treating a local file as trusted. A zero-prevalence script from the Internet zone is what the reporter had, and it is the condition the heuristics are harshest under.

Both halves are differential. "install.ps1 compiles fine" is close to meaningless alone; "the merge base compiles and the candidate does not" is a finding, and so is the reverse.

Every verdict is gated on a positive control

Control
AMSI Microsoft's documented test sample, assembled from fragments, submitted through the same code path in the same process as each measurement. One file per probe invocation exists for that reason: a control in a sibling process only shares a host configuration, which is a weaker claim than it looks.
Defender EICAR, assembled from fragments, through the same MpCmdRun invocation, with quarantined-on-write treated as the control firing.

If a control does not fire, the lane reports that it could not measure and passes with a warning. It never reports clean. That is not theoretical: release-desktop.yml's own comments record three releases that shipped unscanned while their scan step was green, because a runner whose scanner is not live looks exactly like a clean one. On hosted images that is the expected outcome more often than not (real-time protection off, passive mode forced, both drive roots excluded), and this cheap lane deliberately does not spend the ~180 lines release-desktop.yml spends undoing it. The control decides.

Fidelity

The base and head copies are written through [System.IO.File]::WriteAllText with a BOM-less encoder, not Set-Content. install.ps1 is LF-only with no BOM; Set-Content rewrites every line ending to CRLF and on 5.1 prepends a BOM, so the scanner would be handed a file this project never serves and a verdict on it would not transfer to the one users get. A test pins both properties of the shipped file, and names .gitattributes and the HashMismatch hazard as what to check first if it ever fails.

Matching is on FullyQualifiedErrorId, never on message text, which is localised; install.rs already makes that distinction. ScriptContainedMaliciousContent and ScriptHasAdminBlockedContent are kept separate because a signature match can be cleared with a vendor and an administrative policy block cannot, and that difference is the only thing that tells a user what to do.

A syntax error is never reported as a scanner verdict. Conflating them would let a broken candidate masquerade as a detection, or worse, the reverse.

Not a required check

Definitions change daily and outside our control, so a required check that a Microsoft definition push can turn red is a release-blocking hazard. The daily scheduled run exists to notice a new signature that starts matching an unchanged tree, which is otherwise invisible until a user reports it. Engine and definition version are recorded on every run: a verdict without them is not reproducible, and a re-detection after a definition bump is a different event from one on the same definitions.

What it cannot answer

Nothing about Skyhigh, Bitdefender or Kaspersky, which are the products that have actually flagged us. No hosted runner has them, and a Defender verdict is not a proxy for another vendor's. The last step of the job says that out loud on every run, pass or fail, because a run whose summary is only "green" teaches the next reader that the lane proves more than it does.

Verification

  • 600 passed, 6 skipped across tests/security/, including 12 new guards.
  • The probe was run for real on this host, where no AMSI provider exists. That is the entire unmeasured path, and it must produce well-formed JSON saying so rather than crash, otherwise a genuinely absent scanner is reported as a broken lane. A test performs that run.
  • The probe is asserted to compile and never invoke. It is handed the real installer, from a base commit nobody reviewed for the purpose, so an Invoke-Expression creeping in would run a full install inside a measurement step.
  • Both the AMSI sample and EICAR are asserted to be split across string fragments, so this repository is not itself a sample of either. That is the same self-inflicted detection class as the two fixture archives that made Panda flag the GitHub zip (CVE detection report on virus total #9577).
  • One defect found and fixed while smoke-running: in -File mode the argument binder does not split a comma-separated value into an array, so a list of paths arrived as one string and the probe reported "file not found" for files that exist. 5.1 has to be invoked with -File, so this would have been silent on the only interpreter that matters.
  • The lane has not yet run on Windows. Its first real run is the honest test of it, and I will report that result rather than imply it has already measured anything.

@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-15T21:14:52.735790Z 160ee07 Manual request
ℹ️ About Codex in GitHub

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

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

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…actually reports

The reporter in #10805 was not running install.ps1 and watching it misbehave. The script was refused
before its first statement ran, because PowerShell hands a script block to AMSI at COMPILE time. Not
one of the six hardening passes since has measured that, so none can be shown to have fixed it.

`[scriptblock]::Create` on the file's text reproduces that exact path with none of an install's side
effects: no download, no venv, no registry, no shortcut. Nothing is invoked, only compiled, which is
what makes running it on every candidate cheap and safe -- unlike the two-full-installs lane in
windows-installer-differential-ci.yml.

Under **Windows PowerShell 5.1** specifically. That is what install.rs spawns (install.rs:433-440),
what a clean Windows box ships and what the reporter ran; pwsh 7 is a different host with a different
AMSI integration, so its answer does not transfer. `RemoteSigned`, not a relaxed policy -- using
Bypass in the lane built to remove Bypass would be absurd.

The second half scans the same files with Defender's on-demand scanner, each copy stamped with
`Zone.Identifier` `ZoneId=3` first so block-at-first-sight consults the cloud rather than treating a
local file as trusted. A zero-prevalence script from the Internet zone is what the reporter had, and
it is the condition the heuristics are harshest under.

Both halves are differential. "install.ps1 compiles fine" is close to meaningless alone; "the merge
base compiles and the candidate does not" is a finding, and so is the reverse.

## Every verdict is gated on a positive control

  AMSI      Microsoft's documented test sample, assembled from fragments, submitted through the SAME
            code path in the SAME process as each measurement. One file per probe invocation exists
            for that reason: a control in a sibling process only shares a host configuration, which
            is a weaker claim than it looks.
  Defender  EICAR, assembled from fragments, through the same MpCmdRun invocation, with the
            quarantined-on-write case treated as the control firing.

If a control does not fire the lane reports that it could not measure and passes with a warning. It
never reports clean. That is not theoretical: release-desktop.yml's own comments record three
releases that shipped unscanned while their scan step was green, because a runner whose scanner is
not live looks exactly like a clean one. On hosted images that is the expected outcome more often
than not -- real-time protection off, passive mode forced, both drive roots excluded -- and this lane
deliberately does not spend the ~180 lines release-desktop.yml spends undoing it. The control decides.

## Fidelity

The base and head copies are written through `[System.IO.File]::WriteAllText` with a BOM-less
encoder, not `Set-Content`. install.ps1 is LF-only with no BOM; Set-Content rewrites every line
ending to CRLF and on 5.1 prepends a BOM, so the scanner would be handed a file this project never
serves and a verdict on it would not transfer to the one users get. A test pins both properties of
the shipped file, and names `.gitattributes` and the HashMismatch hazard as what to check first if it
ever fails.

Matching is on `FullyQualifiedErrorId`, never on message text, which is localised -- install.rs
already makes that distinction. `ScriptContainedMaliciousContent` and `ScriptHasAdminBlockedContent`
are kept separate because a signature match can be cleared with a vendor and an administrative policy
block cannot, and that difference is the only thing that tells a user what to do.

A syntax error is never reported as a scanner verdict. Conflating them would let a broken candidate
masquerade as a detection, or worse, the reverse.

## Not a required check

Definitions change daily and outside our control, so a required check that a Microsoft definition
push can turn red is a release-blocking hazard. The daily scheduled run exists to notice a new
signature that starts matching an unchanged tree, which is otherwise invisible until a user reports
it. Engine and definition version are recorded on every run: a verdict without them is not
reproducible, and a re-detection after a definition bump is a different event from one on the same
definitions.

## What it cannot answer

Nothing about Skyhigh, Bitdefender or Kaspersky, which are the products that have actually flagged
us. No hosted runner has them, and a Defender verdict is not a proxy for another vendor's. The last
step of the job says that out loud on every run, pass or fail, because a run whose summary is only
"green" teaches the next reader that the lane proves more than it does.

## Verification

- 600 passed, 6 skipped across `tests/security/`, including 12 new guards.
- The probe was run for real on this host, where no AMSI provider exists. That is the entire
  unmeasured path, and it must produce well-formed JSON saying so rather than crash -- otherwise a
  genuinely absent scanner is reported as a broken lane. A test performs that run.
- The probe is asserted to compile and never invoke. It is handed the real installer, from a base
  commit nobody reviewed for the purpose, so an `Invoke-Expression` creeping in would run a full
  install inside a measurement step.
- Both the AMSI sample and EICAR are asserted to be split across string fragments, so this repository
  is not itself a sample of either. That is the same self-inflicted detection class as the two
  fixture archives that made Panda flag the GitHub zip.
- One defect found and fixed while smoke-running: in `-File` mode the argument binder does not split
  a comma-separated value into an array, so a list of paths arrived as one string and the probe
  reported "file not found" for files that exist. 5.1 has to be invoked with `-File`, so this would
  have been silent on the only interpreter that matters.
@danielhanchen
danielhanchen force-pushed the av-fp-amsi-defender-lane branch from c834abe to 0374140 Compare September 15, 2026 07:56
pre-commit-ci Bot and others added 4 commits September 15, 2026 08:22
…ails

The lane wrote the Zone.Identifier stream by appending it to -LiteralPath:

    Set-Content -LiteralPath "$($file.FullName):Zone.Identifier" ... -ErrorAction SilentlyContinue

PowerShell documents exactly one way to address an alternate data stream -- the -Stream parameter --
and -LiteralPath is specified as taking the path "exactly as typed". This repo's own working code
does it correctly at release-desktop.yml:1470.

The failure shape is what makes this worth fixing rather than tidying. If the suffix form does not
bind, the -ErrorAction SilentlyContinue sitting next to it swallows the error: the mark is never
applied, block-at-first-sight never consults the cloud, the scan runs against a MyComputer-zone file,
and the step still prints "clean". A silent downgrade of the exact condition the step exists to
create, reported as the result it was supposed to prove.

Now -Stream with -ErrorAction Stop in a try/catch, and a failed stamp is announced twice: once with
the exception, once as a warning that the file was scanned WITHOUT mark-of-the-web. A weaker scan
than the lane claims to run is fine; a reader not knowing which one they got is not.

A guard pins all three properties. It strips comment lines before applying the ban, because the
comment above the fixed code has to name the broken form to explain it -- a substring search over
the raw file matches its own explanation. That has now caught me three times in this series of
guards, which is a good argument for never grepping a file for a string its own prose is obliged to
contain.
…o does

tests/studio/test_pwsh_calls_use_the_shared_runner.py bans a direct subprocess call to pwsh, and this
file had two. The reason is not tidiness: a direct call shares one $XDG_CACHE_HOME/powershell startup
cache with every other xdist worker, and pwsh dying at startup (PowerShell/PowerShell#24461, 'Stack
overflow.' then SIGABRT) renders as CalledProcessError carrying the whole script -- so an interpreter
crash reads exactly like the script under test having failed. Backend CI run 32341628757 lost 284
tests across 19 files to precisely that, and every one looked like a Windows-installer regression.

run_pwsh takes the argv the call site already built, so this is a one-word change per site and no
invocation flags move.

Worth noting how this was caught, because it says something about the method: this guard lives in
tests/studio/ and never ran against this branch in isolation. It only fired when all ten open PRs
were merged together into one tree and the full suite run against that -- 13,153 passed, and this was
one of two failures that exist in no single branch.
@danielhanchen

Copy link
Copy Markdown
Member Author

Fixed: the mark-of-the-web stamp could fail silently and still print "clean"

The lane wrote the Zone.Identifier stream by appending it to -LiteralPath:

Set-Content -LiteralPath "$($file.FullName):Zone.Identifier" ... -ErrorAction SilentlyContinue

PowerShell documents exactly one way to address an alternate data stream -- the -Stream parameter -- and -LiteralPath is specified as taking the path "exactly as typed". This repo's own working code does it correctly at release-desktop.yml:1470.

The failure shape is what makes this worth fixing rather than tidying. If the suffix form does not bind, the -ErrorAction SilentlyContinue sitting right next to it swallows the error: the mark is never applied, block-at-first-sight never consults the cloud, the scan runs against a MyComputer-zone file, and the step still prints clean. A silent downgrade of the exact condition the step exists to create, reported as the result it was supposed to prove.

Now -Stream with -ErrorAction Stop in a try/catch, and a failed stamp is announced twice: once with the exception, once as a warning that the file was scanned without mark-of-the-web. A weaker scan than the lane claims to run is acceptable; a reader not knowing which one they got is not.

A guard pins all three properties. It strips comment lines before applying the ban, because the comment above the fixed code has to name the broken form in order to explain it -- a substring search over the raw file matches its own explanation. That has now caught me three times across these guards, which is a decent argument for never grepping a file for a string its own prose is obliged to contain.

Also fixed here

tests/security/test_amsi_parse_probe.py started pwsh through a direct subprocess.run at two sites, which tests/studio/test_pwsh_calls_use_the_shared_runner.py bans: a direct call shares one $XDG_CACHE_HOME/powershell startup cache with every xdist worker, and pwsh dying at startup (PowerShell/PowerShell#24461, Stack overflow. then SIGABRT) renders as CalledProcessError carrying the whole script -- so an interpreter crash reads exactly like the script under test having failed. Backend CI run 32341628757 lost 284 tests across 19 files to that, and every one looked like a Windows-installer regression. Now run_pwsh, which takes the argv the call site already built.

Caught only by merging all ten open PRs into one tree and running the full suite: that guard lives in tests/studio/ and never ran against this branch alone.

Three ways the lane could publish clean without having measured the head side:

A candidate that failed to compile for a reason unrelated to a scanner came back with an
errorId and blocked=false. The verdict loop only collected blocked results, so the row was
dropped and, with nothing else blocked, the lane reported clean. A script that does not parse
is now its own verdict and fails the job, because AMSI never got to judge it either.

MpCmdRun's exit code was never read. A scan that did not run produces no threat text, so $hit
was false and the row printed clean. Capture $LASTEXITCODE immediately and treat a non-zero
exit with no match as unscanned, which is the contract release-desktop.yml:1472-1489 already
uses for the same tool.

The AMSI control was a single job-wide flag. -Control runs in the same process as the file it
vouches for, so a live base invocation followed by a head invocation where no provider loaded
let the head answer borrow credibility it had not earned. The control is now a property of the
row, and a row whose own control stayed silent is unmeasured.

A probe that wrote no result file also just vanished from the set, which is the same
false-clean by subtraction, so it is recorded instead.

Eight simulations drive the real verdict logic, extracted from the workflow by step id so it
cannot drift from what CI runs. Six of the eight fail against the previous revision.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 15, 2026 11:22
Whether a block is introduced or pre-existing was decided by comparing counts across the two
sides. That called an install.ps1 block pre-existing whenever the base had a block on any file at
all, setup.ps1 included, and called it introduced whenever the base had none, including when the
base row for that same script was never validly measured. Both send a reader to the wrong commit.
Causality is now looked up per script name against a base row that has to be valid, and an
invalid or absent base row says so instead of guessing.

The summary switch also had no case for the verdict the previous commit introduced, so a
candidate that failed to compile was reported as the probe not completing, which is the opposite
of what happened: the probe ran and gave a definite answer. The unmeasured wording was likewise
still claiming a dead provider is the only way to get there, which stopped being true once a
silent per-row control, an unreadable file and a missing result file all led here.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits September 15, 2026 11:57
…uld not reach the cloud

Two ordering defects, both introduced by the previous commit in this PR.

The unmeasured check returned before the blocked list was ever evaluated, so a script a live
provider genuinely refused went unreported whenever some other invocation happened to write no
result, and the job stayed green on a real detection. Incomplete coverage is a warning; it is not
a reason to stop looking at what was found.

The per-row control gated every classification, including parse errors. A parse error is a
property of the script rather than of the scanner, since the compiler rejects it whether or not a
provider is listening, so a broken candidate in a process whose control stayed silent was filed as
unmeasured and exited zero. Only the BLOCKED verdict actually depends on a live provider, and it
still requires one.

Separately, EICAR proves the local engine scans and nothing more. This lane stamps mark-of-the-web
on every candidate so block-at-first-sight consults the cloud, which is the condition a
zero-prevalence script is judged under and the one the report was made under, and with MAPS off
that half is simply absent while an exit-0 scan still reads as clean. release-desktop.yml:1290-1343
verifies MAPS separately for the same reason. This lane is the cheap one and does not repair the
configuration, so it checks and labels: a clean result that could not reach the cloud now says it
is local signatures only.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…equire block-at-first-sight

The base and head copies were reconstructed from git show captured as
PowerShell text, so CRLF became LF, a byte outside UTF-8 became the
replacement character, trailing blank lines collapsed and a final newline
appeared. The lane promises to scan what ships, so stream the blob
instead. Demonstrated on a blob carrying all three properties.

Whether a script compiles does not depend on AMSI, but the compile
verdict sat after the gate that reports a scanner-less runner as
unmeasured, so a candidate with a syntax error there exited zero.

Cloud readiness checked MAPS reporting and connectivity only, then said
block-at-first-sight could act. With DisableBlockAtFirstSeen set it
cannot, and release-desktop.yml already treats that as fatal.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…failure

The step runs with Continue, so an existing but truncated result file
made ConvertFrom-Json return nothing and the row went in with a null
payload. Such a row iterates no results, so the file left the measured
set without being counted as unmeasured, and another process whose
control fired carried the job to clean. Parse under Stop, check the
shape, and route failures into the no-result list.

Moving the compile verdict ahead of the control gate also put it ahead of
the point where the blocks were derived, so a refusal by a live provider
went unreported whenever another script failed to parse. Derive both
first and print both.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
Calling a .NET static method from PowerShell wraps whatever it threw in a
MethodInvocationException, so the outer FullyQualifiedErrorId is the
generic ParseException regardless of why the parse failed. The id that
separates a scanner refusal from an ordinary syntax error is on the inner
ParseException's Errors collection. Verified by execution: a deliberate
syntax error gives outer ParseException and inner
IfStatementMissingCondition.

Matching the outer id alone meant ScriptContainedMaliciousContent was
never recognised, so not even the positive control could fire and the
lane could only ever report that it had not measured. Walk the exception
chain and record every id found.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 5dbb3a2ba6

ℹ️ About Codex in GitHub

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

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

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

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

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
A Windows checkout with the default core.autocrlf=true rewrites
install.ps1 to CRLF on disk, because .gitattributes carries no *.ps1
rule, so this failed on Windows runners while the bytes the project
serves were unchanged. Found by the cross-platform staging run. The lane
copies blobs out of git precisely so the checkout cannot matter, and the
assertion now looks where the lane looks.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits September 15, 2026 20:04
The Defender verdict kept only head-side results, so a signature that already
flags the merge base read exactly like a regression this change introduced, and
a base-only detection read as a plain clean head rather than the improvement it
is. Per-script base state is now recorded and consulted, with a vanished copy
keyed as unmeasured rather than absent.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The catch around the control write and scan set the control live and printed that
real-time protection blocked the file. A permission or I/O failure under
RUNNER_TEMP, or MpCmdRun failing to launch, took the same path, and every
candidate result after it was then trusted, so an unavailable scanner reporting
no hit could be reported as clean. That is the exact condition this control
exists to catch.

The write and the scan are now separate, and the control is only declared live on
an observation: the control file is gone. Anything else says what failed and
leaves the control unfired.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…n MAPS

Two corrections to the Defender half.

The control accepted absence as a block. This step runs with
ErrorActionPreference Continue, so a non-terminating Set-Content failure did not
even raise and fell straight through to treating the missing file as quarantine;
an ACL, a full disk or a transient I/O error could satisfy the control with no
scanner running. Both writes are terminating now, existence is observed rather
than assumed, and a benign file of the same size is written the same way into the
same directory first. Absence of the EICAR file is only read as Defender when
that identical write succeeded; if the directory is not writable the half reports
no positive control and measures nothing.

Cloud readiness no longer gates on DisableBlockAtFirstSeen. That was right while
the step claimed block-at-first-sight had acted on the mark of the web, and wrong
once it was corrected to say what it does: block-at-first-sight only consults the
cloud on an on-access open, and this lane never opens the copies. Gating on it
labelled a runner whose cloud the on-demand scan can reach as local signatures
only. The preference is still read and still printed alongside the verdict.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…d let a missing manifest reach the verdict

The candidates sit in a directory exempted from on-access scanning and are
measured only by the explicit MpCmdRun scan, so a control that fired by being
quarantined on write proved a provider was live and proved nothing about that
command: an on-demand scanner that silently skipped files would still have been
trusted. The control now lives inside the same exempt root, survives its write,
and is fired by the scan output alone. A control removed before the scan reads it
says the measurement path is unproven rather than counting as a pass.

Separately, when the layout manifest is missing both halves fell back to
enumerating survivors, which cannot notice that an expected candidate is absent,
so a quarantined copy left its siblings to carry the run to a clean verdict. That
condition is now recorded and reaches noResult and unscanned.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 160ee072b8

ℹ️ About Codex in GitHub

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

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

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

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

@danielhanchen
danielhanchen merged commit 89862da into main Sep 15, 2026
47 checks passed
@danielhanchen
danielhanchen deleted the av-fp-amsi-defender-lane branch September 15, 2026 21:33
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…thai#10805 actually reports (unslothai#10994)

* Ask AMSI whether the installer compiles, which is the mechanism unslothai#10805 actually reports

The reporter in unslothai#10805 was not running install.ps1 and watching it misbehave. The script was refused
before its first statement ran, because PowerShell hands a script block to AMSI at COMPILE time. Not
one of the six hardening passes since has measured that, so none can be shown to have fixed it.

`[scriptblock]::Create` on the file's text reproduces that exact path with none of an install's side
effects: no download, no venv, no registry, no shortcut. Nothing is invoked, only compiled, which is
what makes running it on every candidate cheap and safe -- unlike the two-full-installs lane in
windows-installer-differential-ci.yml.

Under **Windows PowerShell 5.1** specifically. That is what install.rs spawns (install.rs:433-440),
what a clean Windows box ships and what the reporter ran; pwsh 7 is a different host with a different
AMSI integration, so its answer does not transfer. `RemoteSigned`, not a relaxed policy -- using
Bypass in the lane built to remove Bypass would be absurd.

The second half scans the same files with Defender's on-demand scanner, each copy stamped with
`Zone.Identifier` `ZoneId=3` first so block-at-first-sight consults the cloud rather than treating a
local file as trusted. A zero-prevalence script from the Internet zone is what the reporter had, and
it is the condition the heuristics are harshest under.

Both halves are differential. "install.ps1 compiles fine" is close to meaningless alone; "the merge
base compiles and the candidate does not" is a finding, and so is the reverse.

## Every verdict is gated on a positive control

  AMSI      Microsoft's documented test sample, assembled from fragments, submitted through the SAME
            code path in the SAME process as each measurement. One file per probe invocation exists
            for that reason: a control in a sibling process only shares a host configuration, which
            is a weaker claim than it looks.
  Defender  EICAR, assembled from fragments, through the same MpCmdRun invocation, with the
            quarantined-on-write case treated as the control firing.

If a control does not fire the lane reports that it could not measure and passes with a warning. It
never reports clean. That is not theoretical: release-desktop.yml's own comments record three
releases that shipped unscanned while their scan step was green, because a runner whose scanner is
not live looks exactly like a clean one. On hosted images that is the expected outcome more often
than not -- real-time protection off, passive mode forced, both drive roots excluded -- and this lane
deliberately does not spend the ~180 lines release-desktop.yml spends undoing it. The control decides.

## Fidelity

The base and head copies are written through `[System.IO.File]::WriteAllText` with a BOM-less
encoder, not `Set-Content`. install.ps1 is LF-only with no BOM; Set-Content rewrites every line
ending to CRLF and on 5.1 prepends a BOM, so the scanner would be handed a file this project never
serves and a verdict on it would not transfer to the one users get. A test pins both properties of
the shipped file, and names `.gitattributes` and the HashMismatch hazard as what to check first if it
ever fails.

Matching is on `FullyQualifiedErrorId`, never on message text, which is localised -- install.rs
already makes that distinction. `ScriptContainedMaliciousContent` and `ScriptHasAdminBlockedContent`
are kept separate because a signature match can be cleared with a vendor and an administrative policy
block cannot, and that difference is the only thing that tells a user what to do.

A syntax error is never reported as a scanner verdict. Conflating them would let a broken candidate
masquerade as a detection, or worse, the reverse.

## Not a required check

Definitions change daily and outside our control, so a required check that a Microsoft definition
push can turn red is a release-blocking hazard. The daily scheduled run exists to notice a new
signature that starts matching an unchanged tree, which is otherwise invisible until a user reports
it. Engine and definition version are recorded on every run: a verdict without them is not
reproducible, and a re-detection after a definition bump is a different event from one on the same
definitions.

## What it cannot answer

Nothing about Skyhigh, Bitdefender or Kaspersky, which are the products that have actually flagged
us. No hosted runner has them, and a Defender verdict is not a proxy for another vendor's. The last
step of the job says that out loud on every run, pass or fail, because a run whose summary is only
"green" teaches the next reader that the lane proves more than it does.

## Verification

- 600 passed, 6 skipped across `tests/security/`, including 12 new guards.
- The probe was run for real on this host, where no AMSI provider exists. That is the entire
  unmeasured path, and it must produce well-formed JSON saying so rather than crash -- otherwise a
  genuinely absent scanner is reported as a broken lane. A test performs that run.
- The probe is asserted to compile and never invoke. It is handed the real installer, from a base
  commit nobody reviewed for the purpose, so an `Invoke-Expression` creeping in would run a full
  install inside a measurement step.
- Both the AMSI sample and EICAR are asserted to be split across string fragments, so this repository
  is not itself a sample of either. That is the same self-inflicted detection class as the two
  fixture archives that made Panda flag the GitHub zip.
- One defect found and fixed while smoke-running: in `-File` mode the argument binder does not split
  a comma-separated value into an array, so a list of paths arrived as one string and the probe
  reported "file not found" for files that exist. 5.1 has to be invoked with `-File`, so this would
  have been silent on the only interpreter that matters.

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

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

* Stamp mark-of-the-web the documented way, and say so when the stamp fails

The lane wrote the Zone.Identifier stream by appending it to -LiteralPath:

    Set-Content -LiteralPath "$($file.FullName):Zone.Identifier" ... -ErrorAction SilentlyContinue

PowerShell documents exactly one way to address an alternate data stream -- the -Stream parameter --
and -LiteralPath is specified as taking the path "exactly as typed". This repo's own working code
does it correctly at release-desktop.yml:1470.

The failure shape is what makes this worth fixing rather than tidying. If the suffix form does not
bind, the -ErrorAction SilentlyContinue sitting next to it swallows the error: the mark is never
applied, block-at-first-sight never consults the cloud, the scan runs against a MyComputer-zone file,
and the step still prints "clean". A silent downgrade of the exact condition the step exists to
create, reported as the result it was supposed to prove.

Now -Stream with -ErrorAction Stop in a try/catch, and a failed stamp is announced twice: once with
the exception, once as a warning that the file was scanned WITHOUT mark-of-the-web. A weaker scan
than the lane claims to run is fine; a reader not knowing which one they got is not.

A guard pins all three properties. It strips comment lines before applying the ban, because the
comment above the fixed code has to name the broken form to explain it -- a substring search over
the raw file matches its own explanation. That has now caught me three times in this series of
guards, which is a good argument for never grepping a file for a string its own prose is obliged to
contain.

* Start pwsh through the shared runner, as every other test in this repo does

tests/studio/test_pwsh_calls_use_the_shared_runner.py bans a direct subprocess call to pwsh, and this
file had two. The reason is not tidiness: a direct call shares one $XDG_CACHE_HOME/powershell startup
cache with every other xdist worker, and pwsh dying at startup (PowerShell/PowerShell#24461, 'Stack
overflow.' then SIGABRT) renders as CalledProcessError carrying the whole script -- so an interpreter
crash reads exactly like the script under test having failed. Backend CI run 32341628757 lost 284
tests across 19 files to precisely that, and every one looked like a Windows-installer regression.

run_pwsh takes the argv the call site already built, so this is a one-word change per site and no
invocation flags move.

Worth noting how this was caught, because it says something about the method: this guard lives in
tests/studio/ and never ran against this branch in isolation. It only fired when all ten open PRs
were merged together into one tree and the full suite run against that -- 13,153 passed, and this was
one of two failures that exist in no single branch.

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

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

* Refuse a clean verdict for anything this lane did not actually measure

Three ways the lane could publish clean without having measured the head side:

A candidate that failed to compile for a reason unrelated to a scanner came back with an
errorId and blocked=false. The verdict loop only collected blocked results, so the row was
dropped and, with nothing else blocked, the lane reported clean. A script that does not parse
is now its own verdict and fails the job, because AMSI never got to judge it either.

MpCmdRun's exit code was never read. A scan that did not run produces no threat text, so $hit
was false and the row printed clean. Capture $LASTEXITCODE immediately and treat a non-zero
exit with no match as unscanned, which is the contract release-desktop.yml:1472-1489 already
uses for the same tool.

The AMSI control was a single job-wide flag. -Control runs in the same process as the file it
vouches for, so a live base invocation followed by a head invocation where no provider loaded
let the head answer borrow credibility it had not earned. The control is now a property of the
row, and a row whose own control stayed silent is unmeasured.

A probe that wrote no result file also just vanished from the set, which is the same
false-clean by subtraction, so it is recorded instead.

Eight simulations drive the real verdict logic, extracted from the workflow by step id so it
cannot drift from what CI runs. Six of the eight fail against the previous revision.

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

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

* Assign causality per script, and say what a broken verdict means

Whether a block is introduced or pre-existing was decided by comparing counts across the two
sides. That called an install.ps1 block pre-existing whenever the base had a block on any file at
all, setup.ps1 included, and called it introduced whenever the base had none, including when the
base row for that same script was never validly measured. Both send a reader to the wrong commit.
Causality is now looked up per script name against a base row that has to be valid, and an
invalid or absent base row says so instead of guessing.

The summary switch also had no case for the verdict the previous commit introduced, so a
candidate that failed to compile was reported as the probe not completing, which is the opposite
of what happened: the probe ran and gave a definite answer. The unmeasured wording was likewise
still claiming a dead provider is the only way to get there, which stopped being true once a
silent per-row control, an unreadable file and a missing result file all led here.

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

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

* Report a real refusal before a coverage gap, and say when Defender could not reach the cloud

Two ordering defects, both introduced by the previous commit in this PR.

The unmeasured check returned before the blocked list was ever evaluated, so a script a live
provider genuinely refused went unreported whenever some other invocation happened to write no
result, and the job stayed green on a real detection. Incomplete coverage is a warning; it is not
a reason to stop looking at what was found.

The per-row control gated every classification, including parse errors. A parse error is a
property of the script rather than of the scanner, since the compiler rejects it whether or not a
provider is listening, so a broken candidate in a process whose control stayed silent was filed as
unmeasured and exited zero. Only the BLOCKED verdict actually depends on a live provider, and it
still requires one.

Separately, EICAR proves the local engine scans and nothing more. This lane stamps mark-of-the-web
on every candidate so block-at-first-sight consults the cloud, which is the condition a
zero-prevalence script is judged under and the one the report was made under, and with MAPS off
that half is simply absent while an exit-0 scan still reads as clean. release-desktop.yml:1290-1343
verifies MAPS separately for the same reason. This lane is the cheap one and does not repair the
configuration, so it checks and labels: a clean result that could not reach the cloud now says it
is local signatures only.

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

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

* Copy the blob, decide compile failures before the control gate, and require block-at-first-sight

The base and head copies were reconstructed from git show captured as
PowerShell text, so CRLF became LF, a byte outside UTF-8 became the
replacement character, trailing blank lines collapsed and a final newline
appeared. The lane promises to scan what ships, so stream the blob
instead. Demonstrated on a blob carrying all three properties.

Whether a script compiles does not depend on AMSI, but the compile
verdict sat after the gate that reports a scanner-less runner as
unmeasured, so a candidate with a syntax error there exited zero.

Cloud readiness checked MAPS reporting and connectivity only, then said
block-at-first-sight could act. With DisableBlockAtFirstSeen set it
cannot, and release-desktop.yml already treats that as fatal.

* Apply the kwarg-spacing formatter to the tests added in this branch

* Reject a malformed probe result, and report blocks alongside a parse failure

The step runs with Continue, so an existing but truncated result file
made ConvertFrom-Json return nothing and the row went in with a null
payload. Such a row iterates no results, so the file left the measured
set without being counted as unmeasured, and another process whose
control fired carried the job to clean. Parse under Stop, check the
shape, and route failures into the no-result list.

Moving the compile verdict ahead of the control gate also put it ahead of
the point where the blocks were derived, so a refusal by a live provider
went unreported whenever another script failed to parse. Derive both
first and print both.

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

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

* Scan the EICAR control with the candidate flags, and exempt the copies from on-access scanning

The control ran without -DisableRemediation while the candidates ran with
it. That flag also makes the explicit scan ignore file exclusions, which
this repository's release scanner records, and the hosted images ship
with both drive roots excluded, so the control scan could be skipped
while the candidate scans worked and the step exited having measured
nothing.

Real-time protection also acts on open and on write, and
-DisableRemediation governs only the explicit scan, so a live provider
could quarantine a laid-out copy mid-stamp and turn a detection into a
missing file. Exempt the directory holding them, which does not weaken
the verdict because the explicit scan ignores exclusions.

* Apply the kwarg-spacing formatter

* Establish the on-access exclusion before the copies are written

Excluding the directory in the Defender step left both earlier steps
exposed: the layout step writes every copy and the AMSI step opens them,
and real-time protection acts on open and on write while
-DisableRemediation governs only the explicit scan. A quarantined copy
then vanishes from the later enumerations and another valid row can carry
both halves to clean. Move it into its own step ahead of the layout, and
read the preference back, because Add-MpPreference is non-terminating
here and a refusal otherwise looks exactly like success.

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

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

* Measure the set that was laid out, not the files that survived

Both loops enumerated the laid-out directory, so a copy quarantined by
real-time protection before they ran left the set entirely: it became
neither an unmeasured row nor a detection, and a surviving sibling could
carry the job to a clean verdict. That is reachable whenever
Add-MpPreference is refused, which the previous commit made visible but
could not prevent. The layout step now records what it wrote and both
loops read that, reporting anything absent into their own verdict.

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

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

* Decode the candidate as UTF-8, and stop claiming block-at-first-sight

Windows PowerShell 5.1 reads a BOM-less file as ANSI and the shipped
installers are BOM-less UTF-8, so Get-Content handed AMSI a mojibake
version of any non-ASCII text. That is the one host this probe exists to
reproduce, and it is also not what irm | iex does.

The on-access exclusion that keeps a detection from quarantining the
evidence also removes the path block-at-first-sight needs: it consults
the cloud only on an on-access open, which this lane never performs. What
the mark of the web plus MAPS buys is an on-demand cloud scan, which is
what the low-prevalence verdicts still reach, so say that instead.

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

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

* Read the AMSI error id off the inner parse error

Calling a .NET static method from PowerShell wraps whatever it threw in a
MethodInvocationException, so the outer FullyQualifiedErrorId is the
generic ParseException regardless of why the parse failed. The id that
separates a scanner refusal from an ordinary syntax error is on the inner
ParseException's Errors collection. Verified by execution: a deliberate
syntax error gives outer ParseException and inner
IfStatementMissingCondition.

Matching the outer id alone meant ScriptContainedMaliciousContent was
never recognised, so not even the positive control could fire and the
lane could only ever report that it had not measured. Walk the exception
chain and record every id found.

* Assert the committed blob has no CRLF, not the working tree

A Windows checkout with the default core.autocrlf=true rewrites
install.ps1 to CRLF on disk, because .gitattributes carries no *.ps1
rule, so this failed on Windows runners while the bytes the project
serves were unchanged. Found by the cross-platform staging run. The lane
copies blobs out of git precisely so the checkout cannot matter, and the
assertion now looks where the lane looks.

* Assign Defender causality per script, the way the AMSI half does

The Defender verdict kept only head-side results, so a signature that already
flags the merge base read exactly like a regression this change introduced, and
a base-only detection read as a plain clean head rather than the improvement it
is. Per-script base state is now recorded and consulted, with a vanished copy
keyed as unmeasured rather than absent.

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

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

* Never infer a fired EICAR control from an exception

The catch around the control write and scan set the control live and printed that
real-time protection blocked the file. A permission or I/O failure under
RUNNER_TEMP, or MpCmdRun failing to launch, took the same path, and every
candidate result after it was then trusted, so an unavailable scanner reporting
no hit could be reported as clean. That is the exact condition this control
exists to catch.

The write and the scan are now separate, and the control is only declared live on
an observation: the control file is gone. Anything else says what failed and
leaves the control unfired.

* Attribute the EICAR control to Defender, and decide cloud readiness on MAPS

Two corrections to the Defender half.

The control accepted absence as a block. This step runs with
ErrorActionPreference Continue, so a non-terminating Set-Content failure did not
even raise and fell straight through to treating the missing file as quarantine;
an ACL, a full disk or a transient I/O error could satisfy the control with no
scanner running. Both writes are terminating now, existence is observed rather
than assumed, and a benign file of the same size is written the same way into the
same directory first. Absence of the EICAR file is only read as Defender when
that identical write succeeded; if the directory is not writable the half reports
no positive control and measures nothing.

Cloud readiness no longer gates on DisableBlockAtFirstSeen. That was right while
the step claimed block-at-first-sight had acted on the mark of the web, and wrong
once it was corrected to say what it does: block-at-first-sight only consults the
cloud on an on-access open, and this lane never opens the copies. Gating on it
labelled a runner whose cloud the on-demand scan can reach as local signatures
only. The preference is still read and still printed alongside the verdict.

* Fire the control through the command the candidates are read with, and let a missing manifest reach the verdict

The candidates sit in a directory exempted from on-access scanning and are
measured only by the explicit MpCmdRun scan, so a control that fired by being
quarantined on write proved a provider was live and proved nothing about that
command: an on-demand scanner that silently skipped files would still have been
trusted. The control now lives inside the same exempt root, survives its write,
and is fired by the scan output alone. A control removed before the scan reads it
says the measurement path is unproven rather than counting as a pass.

Separately, when the layout manifest is missing both halves fell back to
enumerating survivors, which cannot notice that an expected candidate is absent,
so a quarantined copy left its siblings to carry the run to a clean verdict. That
condition is now recorded and reaches noResult and unscanned.

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

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

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant