diff --git a/.gitattributes b/.gitattributes index 81c1690..5dc0efe 100644 --- a/.gitattributes +++ b/.gitattributes @@ -15,3 +15,7 @@ # SAIPEN byte-bound evidence (digest-verified; never convert line endings) -- T-1508. .saipen/recovery/board-scrub/** -text + +# The scenarios migration manifest hashes the published source bytes. +# Keep those text payloads stable even with core.autocrlf=true on Windows. +Scripts/scenarios/** text eol=lf diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e73aed0..104eda9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,8 @@ on: jobs: regs: runs-on: windows-latest + env: + PYTHONIOENCODING: utf-8 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 @@ -25,6 +27,11 @@ jobs: # stubs must break the dependent harnesses, never silently skip. powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_ci_hermetic.ps1 if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Test isolated CI Python launcher and argument forwarding + shell: pwsh + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_ci_python_launcher.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Run integrity suite shell: pwsh run: | @@ -196,7 +203,9 @@ jobs: - name: Test Explorer menu launch and argument contract shell: pwsh run: | - powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_shell_menu.ps1 + # Exercise a recorder that is still live after the old ten-second + # bound; preserve real shell resolution and drive-root assertions. + powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_shell_menu.ps1 -RecorderDelayMilliseconds 12000 if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Test single-instance activation publication shell: pwsh diff --git a/SAITULS.cs b/SAITULS.cs index 77ff4f9..de1efd3 100644 --- a/SAITULS.cs +++ b/SAITULS.cs @@ -7840,7 +7840,7 @@ int DrawAccountDetailPane(Graphics g, int px, int py, int pw, int ph, AccountRow oy += 22; } - return oy - startY + _acctDetailScrollY; + return oy - startY; } void DrawAccountsTab(Graphics g, int x, int y, int w, int h) @@ -8950,9 +8950,10 @@ void SignInFlow(string label, string backend, string provider, string context) // time out into a false READY, and never open a second account to // "help" if they abandon it. var sw = Stopwatch.StartNew(); - while (sw.ElapsedMilliseconds < AuthPollBudgetMs) + while (!_closing && sw.ElapsedMilliseconds < AuthPollBudgetMs) { Thread.Sleep(3000); + if (_closing) return; CliRun r = AccountsExec("status \"" + label + "\"", 20000); var o = ParseEnv(r.Stdout); if (o == null) continue; diff --git a/Scripts/accounts/InstallImage.ps1 b/Scripts/accounts/InstallImage.ps1 index 2ec50f6..85fcd78 100644 --- a/Scripts/accounts/InstallImage.ps1 +++ b/Scripts/accounts/InstallImage.ps1 @@ -10,9 +10,11 @@ function Get-SaiExecutableHash([string]$Path) { function Install-SaiExecutableImage([string]$Source, [string]$Target, [string]$AllowedDirectory) { $directory = (Get-Item -LiteralPath $AllowedDirectory -ErrorAction Stop).FullName $destination = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Target) - if (-not [string]::Equals([IO.Path]::GetDirectoryName($destination).TrimEnd('\'), $directory.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) { + $destinationDirectory = (Get-Item -LiteralPath ([IO.Path]::GetDirectoryName($destination)) -ErrorAction Stop).FullName + if (-not [string]::Equals($destinationDirectory.TrimEnd('\'), $directory.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) { throw "Executable replacement target is outside its owned directory: $destination" } + $destination = Join-Path $destinationDirectory ([IO.Path]::GetFileName($destination)) $sourcePath = (Get-Item -LiteralPath $Source -ErrorAction Stop).FullName $sourceHash = Get-SaiExecutableHash $sourcePath if ((Test-Path -LiteralPath $destination -PathType Leaf) -and diff --git a/Scripts/accounts/SaiAccounts.cs b/Scripts/accounts/SaiAccounts.cs index 45ebe81..76210f0 100644 --- a/Scripts/accounts/SaiAccounts.cs +++ b/Scripts/accounts/SaiAccounts.cs @@ -956,7 +956,16 @@ static Dictionary AntigravityLogout() return resp; } + // In-process seam for an authenticated launch fixture; the shipped CLI + // has no environment variable or command that replaces the native reader. + internal static Func> CredentialProbe = ReadCredential; + public static Dictionary CheckCredential() + { + return CredentialProbe(); + } + + static Dictionary ReadCredential() { IntPtr ptr; bool present = CredReadW("gemini:antigravity", 1, 0, out ptr); var result = Obj(); diff --git a/Scripts/accounts/SaiAccountsHelper.cs b/Scripts/accounts/SaiAccountsHelper.cs index be62a40..79ac833 100644 --- a/Scripts/accounts/SaiAccountsHelper.cs +++ b/Scripts/accounts/SaiAccountsHelper.cs @@ -922,13 +922,20 @@ private static bool IsTestMode() return Environment.GetEnvironmentVariable("SAI_HELPER_TEST_MODE") == "1"; } + private static string ResolveUserSid(string username) + { + if (IsTestMode()) + return "S-1-5-21-999999999-888888888-777777777-" + Math.Abs(username.GetHashCode() % 9000 + 1000); + return ((SecurityIdentifier)new NTAccount(username).Translate(typeof(SecurityIdentifier))).Value; + } + public static bool CreateLocalUser(string username, string password, out string sid, out string error) { sid = null; error = null; if (IsTestMode()) { // Simulated user for hermetic testing - sid = "S-1-5-21-999999999-888888888-777777777-" + Math.Abs(username.GetHashCode() % 9000 + 1000); + sid = ResolveUserSid(username); return true; } @@ -1756,8 +1763,7 @@ private static Dictionary HandleRequest(string op, Dictionary destructive badge", - "destination_sha256": "4d205270e1c725a82774da33c0206e975cc81409c1d3ceb30bb2b84fe516535b" + "destination_sha256": "e11cf70d64a2dd914fecd28e9436ea8ff567877d87c5496eb6b2a6fb3f324796" }, { "source": "MEDIA/IMAGE/PIC/DDS2PNG.py", @@ -688,7 +688,7 @@ "destination": "media/image/convert_dds_to_png.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "3a352449d29408c1295e99363cfcd4f094b864d833a152e0ecdfaef0750aeb41" + "destination_sha256": "e6cb5a2dcc5394a03c93e782629199c059972561f130cb36203d2b1ab13c6a50" }, { "source": "MEDIA/IMAGE/PIC/DDS2TGA.py", @@ -697,7 +697,7 @@ "destination": "media/image/convert_dds_to_tga.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "6552e08eaeb447ea495ba84fc5e5f523761d26fb35feb908e60bfabc0a892a88" + "destination_sha256": "2c2cbff5b8f7d3ecfbc006afecdfe72dbff3148694910b5087a1208ff428af28" }, { "source": "MEDIA/IMAGE/PIC/PNG2DDS.py", @@ -706,7 +706,7 @@ "destination": "media/image/convert_png_to_dds.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "abb46c82e9fa10e797038d11b46cb52b955d078f888071e3ec91830e4169ff6a" + "destination_sha256": "fd93efc40153bfefc75276c63dbadc6b5b86e5dd9546ea3ed3ce9e5b9350bcf9" }, { "source": "MEDIA/IMAGE/PIC/REP_DDS.ps1", @@ -723,7 +723,7 @@ "destination": "media/image/replace_dds_with_png.py", "active": false, "reason": "main1.png repack helper; registry-listed but DISABLED (replace-in-place semantics unproven)", - "destination_sha256": "de18e81fefef3478d2e439e3849e4d5bd90bfe96020294d6237dcbc036116159" + "destination_sha256": "c8ed21c56d6c914c13ba27f7675fa8c7e7b65f7a36ab31af8f52c8abf400f5b1" }, { "source": "MEDIA/IMAGE/PIC/TGA2BW.py", @@ -741,7 +741,7 @@ "destination": "media/image/convert_tga_to_dds.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "153a7e4465d19a686b9be801bc60c5923dcf75d3f155176e6cdfc919efbd19e6" + "destination_sha256": "2b0f46f5ab4ddf2a4b916f6a8ca5d468b58df6a130566ad3f9385a3df089da67" }, { "source": "MEDIA/IMAGE/PIC/TGA2DDS2.py", @@ -750,7 +750,7 @@ "destination": "media/image/convert_tga_to_dds_alt.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "ff64a571db68a847beb94080da67e6999450caba609703132873c85ef2010905" + "destination_sha256": "c753fa0042926b0da47d48061f65d3ef3e92f12ee6b8c8baf171b45d6e79e1cb" }, { "source": "MEDIA/IMAGE/PIC/UPS_TGA.py", @@ -1001,7 +1001,7 @@ "destination": "media/video/COMPRESS_V.sh", "active": true, "reason": "Git Bash AV1 batch compressor; source dirs moved to config; bash dependency verified on PATH", - "destination_sha256": "a5524b4589136dddb871f2051b6c52e6f064b16db15ccc1e05dbfd6ab653e220" + "destination_sha256": "a05b34317ab6f7b0b733229f63774b407f60cdb929be11a3afcfd1bd1fecfb69" }, { "source": "MEDIA/VIDEO/VID/GOV.ps1", diff --git a/tests/account_identity_contract_test.cs b/tests/account_identity_contract_test.cs index ad3dd8c..c05caf1 100644 --- a/tests/account_identity_contract_test.cs +++ b/tests/account_identity_contract_test.cs @@ -62,7 +62,11 @@ static bool Equal(Bitmap left, Bitmap right) { for (int y = 0; y < left.Height; y++) for (int x = 0; x < left.Width; x++) - if (left.GetPixel(x, y) != right.GetPixel(x, y)) return false; + if (left.GetPixel(x, y) != right.GetPixel(x, y)) + { + Console.WriteLine("PIXEL_DIFF x=" + x + " y=" + y); + return false; + } return true; } [STAThread] @@ -82,8 +86,14 @@ static int Main() object row = Row("AG1", "antigravity", Alice); Set(form, "_accounts", Rows(row)); Set(form, "_accountsRuntime", Rows(row)); Set(form, "_selectedAccount", "contract-AG1"); + // The invisible fixture has not had a first paint. Real GDI + // font initialization changes even the unchanged subtitle on + // hosted Windows; initialize it before comparing identities. + using (var warmup = Render(form, row, 640, 540)) { } using (var same = Render(form, row, 640, 540)) { + using (var unchanged = Render(form, row, 640, 540)) + Check(Equal(same, unchanged), "unchanged identity rendering is stable before comparisons"); Set(row, "RuntimeIdentityFp", Bob); using (var distinct = Render(form, row, 640, 540)) { diff --git a/tests/ci_fixtures.ps1 b/tests/ci_fixtures.ps1 index 04ea1ec..84e14ea 100644 --- a/tests/ci_fixtures.ps1 +++ b/tests/ci_fixtures.ps1 @@ -48,6 +48,24 @@ function New-StubCommand([string]$path, [string]$name) { # A resolvable Application command is all the suite needs: the launcher and # the menu installer resolve it with Get-Command and never run it. Exiting 0 # keeps an accidental invocation from looking like an agent crash. + if ($name -eq 'opencode.cmd') { + # SAIPATCH resolves the executable behind an npm-style shim, then + # fingerprints it. An echo-only .cmd satisfies Get-Command but cannot + # satisfy that contract. Build a harmless, explicitly unsupported host + # from source; the existing build-specific tier stays separate. + $exe = Join-Path (Split-Path -Parent $path) 'opencode.exe' + if (-not (Test-Path -LiteralPath $exe)) { + $source = Join-Path $StubRoot 'opencode-fixture.cs' + 'using System; public static class Fixture { public static int Main(string[] args) { Console.WriteLine("SAITULS test fixture"); return 0; } }' | + Set-Content -LiteralPath $source -Encoding UTF8 + & $cscExe /nologo /target:exe "/out:$exe" $source + if ($LASTEXITCODE -ne 0) { throw 'OpenCode fixture compilation failed' } + } + @('@echo off', 'rem SAITULS test fixture -- not a vendor CLI.', + 'set "dp0=%~dp0"', '"%dp0%opencode.exe" %*', 'exit /b %errorlevel%') | + Set-Content -LiteralPath $path -Encoding Ascii + return + } $lines = @( '@echo off' "rem SAITULS test fixture -- a resolvable stand-in for the real $name." @@ -78,7 +96,11 @@ function Resolve-Application([string]$name) { if (-not $Verify) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null foreach ($stub in $stubs) { - if (Test-Path -LiteralPath $stub.Path) { + if ((Test-Path -LiteralPath $stub.Path) -and $stub.Name -eq 'opencode.cmd' -and + (Get-Content -LiteralPath $stub.Path -Raw) -match 'SAITULS test fixture') { + New-StubCommand $stub.Path $stub.Name + Write-Host "MAKE complete owned OpenCode fixture $($stub.Path)" + } elseif (Test-Path -LiteralPath $stub.Path) { Write-Host "KEEP $($stub.Name) stub already present $($stub.Path)" } else { New-StubCommand $stub.Path $stub.Name @@ -103,7 +125,8 @@ if (-not $Verify) { } else { $pythonw = Resolve-Application 'pythonw.exe' if (-not $pythonw) { throw 'pythonw.exe is not on PATH; cannot provision the Windows Python launcher' } - Copy-Item -LiteralPath $pythonw.Source -Destination $pywExe -Force + . (Join-Path $PSScriptRoot 'ci_python_launcher.ps1') + New-SaiCiPythonLauncher $pythonw.Source $pywExe Write-Host "MAKE Windows Python launcher $pywExe (from $($pythonw.Source))" } } @@ -131,6 +154,14 @@ foreach ($stub in $stubs) { Assert-Prereq "$($stub.Name) resolves as an application" ($null -ne $resolved) ` $(if ($resolved) { $resolved.Source } else { 'not on PATH -- run this script without -Verify, or install the real CLI' }) } +if (Test-Path -LiteralPath (Join-Path $binDir 'opencode.cmd')) { + $shimText = Get-Content -LiteralPath (Join-Path $binDir 'opencode.cmd') -Raw + if ($shimText -match 'SAITULS test fixture') { + Assert-Prereq 'the OpenCode fixture shim has an executable target' ( + (Test-Path -LiteralPath (Join-Path $binDir 'opencode.exe') -PathType Leaf) -and + $shimText.Contains('"%dp0%opencode.exe"')) 'source-built unsupported test host; no vendor service' + } +} Assert-Prereq 'the global Vintage skill exists' (Test-Path -LiteralPath $vintageSkill -PathType Leaf) $vintageSkill Assert-Prereq 'the Windows Python launcher exists' (Test-Path -LiteralPath $pywExe -PathType Leaf) ` "$pywExe -- a shell verb resolves pyw.exe only from the Windows directory and System32" diff --git a/tests/ci_python_launcher.ps1 b/tests/ci_python_launcher.ps1 new file mode 100644 index 0000000..04848ed --- /dev/null +++ b/tests/ci_python_launcher.ps1 @@ -0,0 +1,44 @@ +# CI-only launcher: pythonw.exe depends on DLLs beside its installed executable. +# Copying that executable to Windows makes ShellExecute succeed while Python +# fails to load. Keep the real interpreter in place and forward the raw Windows +# argument tail, including the intentionally awkward drive-root quoting. +function New-SaiCiPythonLauncher([string]$Pythonw, [string]$Destination) { + $compiler = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe' + if (-not (Test-Path -LiteralPath $Pythonw -PathType Leaf)) { throw 'pythonw.exe not found' } + if (Test-Path -LiteralPath $Destination) { throw 'Refusing to replace an existing launcher' } + $encodedPath = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes([IO.Path]::GetFullPath($Pythonw))) + $source = [IO.Path]::GetTempFileName() + '.cs' + try { + @" +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +internal static class SaiCiPythonLauncher { + [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] + private static extern IntPtr GetCommandLineW(); + [STAThread] + private static int Main() { + try { + string line = Marshal.PtrToStringUni(GetCommandLineW()).TrimStart(); + int end = line.StartsWith("\"") ? line.IndexOf('"', 1) + 1 : line.IndexOf(' '); + string tail = end < 0 ? "" : line.Substring(end).TrimStart(); + var start = new ProcessStartInfo { + FileName = Encoding.Unicode.GetString(Convert.FromBase64String("$encodedPath")), + Arguments = tail, UseShellExecute = false, CreateNoWindow = true + }; + using (var child = Process.Start(start)) { + child.WaitForExit(); + return child.ExitCode; + } + } catch { return 1; } + } +} +"@ | Set-Content -LiteralPath $source -Encoding UTF8 + & $compiler /nologo /target:winexe "/out:$Destination" $source + if ($LASTEXITCODE -ne 0) { throw 'CI Python launcher compilation failed' } + } finally { + Remove-Item -LiteralPath $source -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath ($source.Substring(0, $source.Length - 3)) -Force -ErrorAction SilentlyContinue + } +} diff --git a/tests/credential_probe_fixture.cs b/tests/credential_probe_fixture.cs new file mode 100644 index 0000000..0a71ff6 --- /dev/null +++ b/tests/credential_probe_fixture.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; + +// Compiled only by the native launch harness, never by the production build. +static class CredentialProbeFixture +{ + static int Main(string[] args) + { + SaiAccounts.CredentialProbe = delegate { + return new Dictionary { + { "credential_present", Environment.GetEnvironmentVariable("SAI_FIXTURE_CREDENTIAL_PRESENT") == "1" } + }; + }; + return SaiAccounts.Main(args); + } +} diff --git a/tests/saipatch_ctrlv_e2e.py b/tests/saipatch_ctrlv_e2e.py index 6d855ad..e91c7fc 100644 --- a/tests/saipatch_ctrlv_e2e.py +++ b/tests/saipatch_ctrlv_e2e.py @@ -7,6 +7,7 @@ import json import subprocess import sys +import tempfile import time from pathlib import Path @@ -16,15 +17,17 @@ def main() -> int: - out = Path(r"V:\_TEMP_\opencode\ctrlv-e2e.json") - out.parent.mkdir(parents=True, exist_ok=True) - for suffix in (".json", ".ready"): - p = out.with_suffix(suffix) - if p.exists(): - p.unlink() + with tempfile.TemporaryDirectory(prefix="saituls-ctrlv-") as scratch: + return run(Path(scratch) / "ctrlv-e2e.json") + + +def run(out: Path) -> int: + startup = subprocess.STARTUPINFO() + startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW + startup.wShowWindow = subprocess.SW_HIDE proc = subprocess.Popen( [sys.executable, str(HERE / "saipatch_ctrlv_receiver.py"), "--out", str(out)], - creationflags=subprocess.CREATE_NEW_CONSOLE) + creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=startup) try: ready = out.with_suffix(".ready") deadline = time.monotonic() + 30 diff --git a/tests/saituls_accounts_flow_test.cs b/tests/saituls_accounts_flow_test.cs index 98473da..7b5736e 100644 --- a/tests/saituls_accounts_flow_test.cs +++ b/tests/saituls_accounts_flow_test.cs @@ -255,7 +255,8 @@ static int Main(string[] args) bool focused = args.Length == 1 && args[0] == "--offline-start-and-switch"; bool identityFocused = args.Length == 1 && args[0] == "--identity-status-and-switch"; bool catalogFocused = args.Length == 1 && args[0] == "--provider-catalog-and-layout"; - if (args.Length > 0 && !focused && !identityFocused && !catalogFocused) + bool lifetimeFocused = args.Length == 1 && args[0] == "--window-lifetime-and-scroll"; + if (args.Length > 0 && !focused && !identityFocused && !catalogFocused && !lifetimeFocused) { Console.WriteLine("FAIL unknown runtime test selection"); return 1; @@ -281,7 +282,12 @@ static int Main(string[] args) try { - if (catalogFocused) + if (lifetimeFocused) + { + TestSignInWatchStopsOnClose(); + TestAccountDetailHeightDoesNotGrowWithScroll(); + } + else if (catalogFocused) { T45ProviderCatalogIsTheDialogsSingleSource(); T46PlannedProvidersCannotNameABackend(); @@ -320,6 +326,8 @@ static int Main(string[] args) Test16FailedConnectRendersTheRealError(); Test17ConnectSuccessShowsOnline(); Test18SignInIsNotAConsoleLaunch(); + TestSignInWatchStopsOnClose(); + TestAccountDetailHeightDoesNotGrowWithScroll(); Test19SignInNeverTouchesAWorkdir(); Test20SignInStartsAnOfflineContextFirst(); Test21SignInOnAnOnlineAccountSkipsTheContextStart(); @@ -415,8 +423,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0", "saipen_verdict=RUNTIME_STALE"); Saituls.SaitulsForm f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("SAIPEN"), 30000); Check(LaunchCall("AG2") == null, "T288a a stale machine runtime launches no console", Show()); @@ -430,8 +438,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0", "saipen_verdict=READY"); f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("Launched"), 30000); string[] launch = LaunchCall("AG2"); @@ -444,8 +452,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0", "saipen_verdict=PROJECT_LIFECYCLE_DENIED"); f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("Launched"), 30000); Check(LaunchCall("AG2") != null, "T288c a lifecycle refusal still opens the console that repairs it", Show()); @@ -455,8 +463,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0"); f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("Launched"), 30000); Check(LaunchCall("AG2") != null && !Note(f).Contains("SAIPEN"), @@ -854,7 +862,7 @@ static void Test18SignInIsNotAConsoleLaunch() Select(f, "AG2"); Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); Check(HasCall("auth", "AG2"), "T18a SIGN IN issues the dedicated auth operation", Show()); Check(LaunchCall("AG2") == null, "T18b SIGN IN never issues a console launch", Show()); @@ -864,6 +872,55 @@ static void Test18SignInIsNotAConsoleLaunch() } // ------------------------------------------------------------------- T19 + static void TestSignInWatchStopsOnClose() + { + Saituls.SaitulsForm f = MakeForm(true); + Select(f, "AG2"); + Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); + Exception failure = null; + var watch = new Thread(delegate() { + try { M(f, "SignInFlow", "AG2", "managed_windows_user", "antigravity", "test-secondary"); } + catch (Exception ex) { failure = ex; } + }); + watch.IsBackground = true; + watch.Start(); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 20000); + Check(HasCall("auth", "AG2"), "sign-in watch starts before testing close", Show()); + f.Dispose(); + Check(watch.Join(5000), "closing the window terminates its sign-in watch", "the owned worker remained alive"); + Check(failure == null, "closing the sign-in watch raises no worker error", Convert.ToString(failure)); + } + + static void TestAccountDetailHeightDoesNotGrowWithScroll() + { + var f = MakeForm(true); + Select(f, "AG2"); + SF(f, "_acctAdvancedExpanded", true); + using (var image = new Bitmap(900, 700)) + using (var g = Graphics.FromImage(image)) + { + SetOf(f, "_acctDetailScrollY", 0); + int first = (int)M(f, "DrawAccountDetailPane", g, 0, 0, 600, 700, Row(f, "AG2")); + SetOf(f, "_acctDetailScrollY", 100); + int scrolled = (int)M(f, "DrawAccountDetailPane", g, 0, 0, 600, 700, Row(f, "AG2")); + Check(first > 0 && scrolled == first, + "account detail scroll does not grow its own content height", first + " -> " + scrolled); + } + f.Dispose(); + } + + static void PaintAccountsAtBottom(Saituls.SaitulsForm form, Graphics graphics) + { + // The advanced controls can extend below the viewport. Emulate a + // scroll to the end and its following paint, including normal hitbox + // reset; clicking an offscreen button is not a real UI route. + SF(form, "_acctDetailScrollY", 5000); + ((IList)F(form, "Buttons")).Clear(); + M(form, "DrawAccountsTab", graphics, 0, 0, 900, 700); + ((IList)F(form, "Buttons")).Clear(); + M(form, "DrawAccountsTab", graphics, 0, 0, 900, 700); + } + // The whole point of PART 1: no workdir anywhere on the sign-in path. Not // on the command line, not in the note, and the form must not even need a // usable workdir -- so this one runs with the saved workdir cleared. @@ -873,7 +930,7 @@ static void Test19SignInNeverTouchesAWorkdir() Select(f, "AG2"); Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); bool anyFlag = false; foreach (string[] a in Calls()) @@ -898,7 +955,7 @@ static void Test20SignInStartsAnOfflineContextFirst() Select(f, "AG2"); Arm("offline_status_calls=1", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); Check(ContextCall("start", "AG2") != null, "T20a an OFFLINE AG2 starts its own context before signing in", Show()); @@ -917,7 +974,7 @@ static void Test21SignInOnAnOnlineAccountSkipsTheContextStart() Select(f, "AG2"); Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); Check(ContextCall("start", "AG2") == null, "T21a an ONLINE AG2 + SIGN IN goes straight to auth", Show()); @@ -1258,7 +1315,7 @@ static void Test29hDiagnosticsCarryTheIdentity() SF(f, "_acctAdvancedExpanded", true); var bmp = new Bitmap(900, 700); using (var g = Graphics.FromImage(bmp)) - M(f, "DrawAccountsTab", g, 0, 0, 900, 700); + PaintAccountsAtBottom(f, g); var buttons = (IList)F(f, "Buttons"); object copy = null; @@ -1746,7 +1803,7 @@ static void T40NoTokenMaterialInTheDiagnostics() SF(f, "_acctAdvancedExpanded", true); var bmp = new Bitmap(900, 700); using (var g = Graphics.FromImage(bmp)) - M(f, "DrawAccountsTab", g, 0, 0, 900, 700); + PaintAccountsAtBottom(f, g); object copy = null; foreach (object b in (IList)F(f, "Buttons")) { diff --git a/tests/shell_probe_wait.ps1 b/tests/shell_probe_wait.ps1 new file mode 100644 index 0000000..5b5a132 --- /dev/null +++ b/tests/shell_probe_wait.ps1 @@ -0,0 +1,19 @@ +# Wait on the exact hidden recorder process owned by the shell test. A fixed +# startup sleep races a cold Python/launcher; a completed process also makes +# it safe to remove the disposable script and result files. +# A cold system launcher on hosted Windows can take more than ten seconds. +# Keep a finite completion bound; timeout still fails and retains the sandbox. +function Wait-SaiShellProbeProcess([IntPtr]$Handle, [uint32]$TimeoutMilliseconds = 60000) { + if ($Handle -eq [IntPtr]::Zero) { + return @{ completed = $false; wait = 'NO_PROCESS_HANDLE'; exit = $null } + } + try { + $waitCode = [SaiShellExec]::WaitForSingleObject($Handle, $TimeoutMilliseconds) + $exitCode = [uint32]0 + $gotExit = [SaiShellExec]::GetExitCodeProcess($Handle, [ref]$exitCode) + return @{ completed = ($waitCode -eq 0); wait = $waitCode + exit = $(if ($gotExit) { $exitCode } else { $null }) } + } finally { + [void][SaiShellExec]::CloseHandle($Handle) + } +} diff --git a/tests/test_account_console_titles.py b/tests/test_account_console_titles.py index 75f7691..1eed0b9 100644 --- a/tests/test_account_console_titles.py +++ b/tests/test_account_console_titles.py @@ -126,7 +126,8 @@ def check_antigravity_result(self, launched): self.assertEqual(payload["expected_title"], title) self.assertEqual(payload["expected_account"], account) self.assertEqual(payload["arguments"], ["--dangerously-skip-permissions"]) - self.assertEqual(os.path.normcase(payload["cwd"]), os.path.normcase(workdir)) + self.assertEqual(os.path.normcase(os.path.realpath(payload["cwd"])), + os.path.normcase(os.path.realpath(workdir))) self.assertEqual(payload["console_process_count"], 2, "guard and vendor must share one console") self.assertEqual(payload["console_process_count_after"], 2, "the guard lives until its vendor exits") self.assertTrue(payload["sid"].startswith("S-1-5-21-")) diff --git a/tests/test_ci_python_launcher.ps1 b/tests/test_ci_python_launcher.ps1 new file mode 100644 index 0000000..33543f2 --- /dev/null +++ b/tests/test_ci_python_launcher.ps1 @@ -0,0 +1,66 @@ +param([string]$Implementation = (Join-Path $PSScriptRoot 'ci_python_launcher.ps1')) +$ErrorActionPreference = 'Stop' +. $Implementation +Add-Type -TypeDefinition @' +using System.Runtime.InteropServices; +public static class SaiLauncherErrorMode { + [DllImport("kernel32.dll")] public static extern uint SetErrorMode(uint mode); +} +'@ +$previousErrorMode = [SaiLauncherErrorMode]::SetErrorMode(0x8003) +$sandbox = Join-Path ([IO.Path]::GetTempPath()) ('saituls-python-launcher-' + [Guid]::NewGuid().ToString('N')) +$fails = 0 +function Check([string]$Name, [bool]$Ok) { + if ($Ok) { Write-Host "PASS $Name" } else { Write-Host "FAIL $Name"; $script:fails++ } +} +New-Item -ItemType Directory -Path $sandbox | Out-Null +try { + $launcher = Join-Path $sandbox 'isolated launcher.exe' + $recorder = Join-Path $sandbox 'argument recorder.pyw' + $result = Join-Path $sandbox 'result.json' + # The same recorder tests the real installed interpreter and isolated shim. + @' +import json, pathlib, sys +pathlib.Path(__file__).with_name('result.json').write_text(json.dumps(sys.argv[1:]), encoding='utf-8') +sys.exit(23) +'@ | Set-Content -LiteralPath $recorder -Encoding UTF8 + $pythonw = (Get-Command pythonw.exe -CommandType Application | Select-Object -First 1).Source + New-SaiCiPythonLauncher $pythonw $launcher + $psi = New-Object Diagnostics.ProcessStartInfo + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.WorkingDirectory = $sandbox + # A real installation must not be rescued by interpreter DLLs on PATH. + # The installed pythonw still finds its DLLs beside itself; a copied + # pythonw in an unrelated directory must prove independent launchability. + $psi.EnvironmentVariables['PATH'] = $env:SystemRoot + ';' + (Join-Path $env:SystemRoot 'System32') + # End with a quoted drive root exactly like the Explorer verb. The shim + # must preserve the Python parser's raw input, not repair this quoting. + $psi.Arguments = '"' + $recorder + '" "with spaces" "" "' + [char]0x00F5 + '" "C:\"' + $psi.FileName = $pythonw + $direct = [Diagnostics.Process]::Start($psi) + if (-not $direct.WaitForExit(10000)) { throw 'Direct interpreter timed out' } + Check 'known-good installed interpreter records arguments' (Test-Path -LiteralPath $result) + if (-not (Test-Path -LiteralPath $result)) { throw 'Known-good interpreter unavailable' } + $expected = [IO.File]::ReadAllText($result) + Check 'known-good interpreter returns deliberate nonzero status' ($direct.ExitCode -eq 23) + Remove-Item -LiteralPath $result -Force + $psi.FileName = $launcher + $forwarded = [Diagnostics.Process]::Start($psi) + if (-not $forwarded.WaitForExit(10000)) { throw 'Isolated launcher timed out' } + Check 'isolated launcher runs the real Python worker' (Test-Path -LiteralPath $result) + Check 'isolated launcher preserves raw Windows arguments' ((Test-Path -LiteralPath $result) -and [IO.File]::ReadAllText($result) -ceq $expected) + Check 'isolated launcher propagates child failure' ($forwarded.ExitCode -eq 23) + $direct.Dispose() + $forwarded.Dispose() +} finally { + [void][SaiLauncherErrorMode]::SetErrorMode($previousErrorMode) + $resolved = [IO.Path]::GetFullPath($sandbox) + $tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' + if (-not $resolved.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -or + (Split-Path $resolved -Leaf) -notlike 'saituls-python-launcher-*') { throw 'Unsafe cleanup target' } + Remove-Item -LiteralPath $resolved -Recurse -Force +} +if ($fails) { Write-Host "FAILED ($fails failures)"; exit 1 } +Write-Host 'PASS (0 failures)' +exit 0 diff --git a/tests/test_consoles_launcher.py b/tests/test_consoles_launcher.py index e9ba7b0..be8da65 100644 --- a/tests/test_consoles_launcher.py +++ b/tests/test_consoles_launcher.py @@ -58,6 +58,58 @@ def strip_csharp_comments(text): LAUNCHER_CODE = strip_powershell_comments(LAUNCHER_SOURCE) +SUITE_ENV = None + + +def console_test_environment(env=None): + """Resolve only disposable CLI/account fixtures, never operator services. + + The account transport is a compiled recording stub; integration with the + real engine is covered separately by test_sai_accounts.py. + """ + global SUITE_ENV + if SUITE_ENV is None: + engine = build_stub_engine("sai-accounts", stdout_env="SAITULS_TEST_ACCOUNTS") + root = Path(engine).parent / "console-fixtures" + root.mkdir(exist_ok=True) + bindir = root / "bin" + bindir.mkdir(exist_ok=True) + for name in ("claude", "codex", "agy", "node", "cline", "opencode"): + (bindir / (name + ".cmd")).write_bytes(b"@echo off\r\nexit /b 0\r\n") + script = root / "zcode.cjs" + script.write_text("// Resolution-only test fixture; no provider code.\n", encoding="utf-8") + accounts = [] + for provider, locators in ( + ("claude", [str(Path(os.environ["USERPROFILE"]) / ".claude"), + str(Path(os.environ["USERPROFILE"]) / ".claude-account2")]), + ("codex", [str(Path(os.environ["USERPROFILE"]) / ".codex")]), + ("antigravity", [os.environ["USERNAME"], "console-fixture-ag2"]), + ): + for index, locator in enumerate(locators, 1): + prefix = {"claude": "CL", "codex": "CX", "antigravity": "AG"}[provider] + kind = "windows-user" if provider == "antigravity" else "profile-dir" + accounts.append({ + "account_id": "%s:%s:%016x" % (provider, kind, index), + "provider_id": provider, "display_name": "%s %s" % (provider.title(), index), + "compact_label": prefix + str(index), "operational_state": "ENABLED", + "hidden": False, "provider_metadata": { + "windows_user" if kind == "windows-user" else "profile_locator": locator}, + }) + SUITE_ENV = { + "PATH": str(bindir) + os.pathsep + os.environ["PATH"], + "ZCODE_CLI": str(script), "SAI_ACCOUNTS_EXE": engine, + "SAITULS_TEST_ACCOUNTS": json.dumps({"schema": "sai.accounts/list/1", "accounts": accounts}), + "STUB_EXIT": "0", "STUB_STDERR": "", "STUB_ARGV_FILE": "", + "SAITULS_CONSOLE_LOG": str(root / "launch.log"), + } + merged = dict(os.environ) + # PS7's module path can shadow the PS5 built-ins used by these children. + merged = {key: value for key, value in merged.items() if key.upper() != "PSMODULEPATH"} + merged.update(SUITE_ENV) + if env: + merged.update(env) + return merged + def run_selftest(*extra, registry_path=None, env=None, federation="off"): """Every suite here runs STANDALONE unless it says otherwise. @@ -69,16 +121,15 @@ def run_selftest(*extra, registry_path=None, env=None, federation="off"): """ cmd = ["powershell", "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(LAUNCHER), "-SelfTest", "-Federation", federation] + list(extra) - merged = dict(os.environ) - if env: - merged.update(env) + merged = console_test_environment(env) completed = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(REPO), env=merged) text = (completed.stdout or "").strip() start = text.find("{") payload = json.loads(text[start:]) if start >= 0 else None - return completed.returncode, payload, completed.stderr + diagnostic = completed.stderr or (text if completed.returncode else "") + return completed.returncode, payload, diagnostic def is_template(profile): """A profile that renders one console per canonical account, not a console.""" @@ -186,7 +237,7 @@ def test_console_launcher_remains_non_elevated(self): def test_project_first_title(self): with tempfile.TemporaryDirectory(prefix="saituls-console-") as tmp: - project = Path(tmp) / "MyProject" + project = (Path(tmp) / "MyProject").resolve() project.mkdir() rc, payload, stderr = run_selftest("-Profile", "claude-1", "-WorkDir", str(project)) @@ -441,9 +492,7 @@ def test_existing_tool_entries_are_unchanged(self): INSTALLER_SOURCE = INSTALLER.read_text(encoding="utf-8") def ps(script, env=None): - merged = dict(os.environ) - if env: - merged.update(env) + merged = console_test_environment(env) completed = subprocess.run( ["powershell", "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "[Console]::OutputEncoding=[Text.Encoding]::UTF8; " @@ -495,6 +544,28 @@ def test_absent_engine_yields_no_accounts_and_no_exception(self): self.assertEqual(rc, 0, err) self.assertEqual(out, "0") + def test_missing_cli_still_reports_an_unresolved_profile(self): + with tempfile.TemporaryDirectory(prefix="saituls-no-cli-") as tmp: + rc, payload, stderr = run_selftest( + "-Profile", "claude-1", env={"PATH": tmp}, federation="off") + self.assertEqual(rc, 0, stderr) + self.assertFalse(payload["ok"]) + row = profile_row(payload, "claude-1") + self.assertFalse(row["Resolved"]) + self.assertEqual(row["ErrorCategory"], "EXECUTABLE_MISSING") + + def test_shared_profiles_are_bound_to_the_fixture_engine(self): + rc, payload, stderr = run_selftest(federation="on") + self.assertEqual(rc, 0, stderr) + # PowerShell can preserve an 8.3 parent while Python expands it. + # Bind the actual fixture file, including rejection of other engines. + self.assertTrue(os.path.samefile( + payload["federation"]["engine"], + console_test_environment()["SAI_ACCOUNTS_EXE"])) + shared = [row for row in payload["profiles"] if row["Origin"] == "shared"] + self.assertTrue(shared) + self.assertTrue(all(row["Command"] == payload["federation"]["engine"] for row in shared)) + class AccountProfileShapeTests(unittest.TestCase): """The adapter's launch shape, proven on every machine. @@ -572,8 +643,7 @@ class FederationTests(unittest.TestCase): """The control plane adds accounts. It never takes any away.""" def setUp(self): - if not engine_is_installed(): - self.skipTest("SAI Accounts control plane is not installed on this machine") + self.assertTrue(engine_is_installed(), "compiled account fixture did not resolve") def federated(self): rc, payload, stderr = run_selftest(federation="on") @@ -646,7 +716,7 @@ def test_codex_shared_profiles_use_the_four_part_shape(self): def test_a_workdir_with_spaces_stays_exactly_one_argument(self): with tempfile.TemporaryDirectory(prefix="saituls-console-") as tmp: - project = Path(tmp) / "My Big Project 2" + project = (Path(tmp) / "My Big Project 2").resolve() project.mkdir() rc, payload, stderr = run_selftest("-WorkDir", str(project), federation="on") self.assertEqual(rc, 0, stderr) @@ -659,7 +729,7 @@ def test_a_workdir_with_spaces_stays_exactly_one_argument(self): def test_a_unicode_workdir_survives_intact(self): with tempfile.TemporaryDirectory(prefix="saituls-console-") as tmp: - project = Path(tmp) / "проект Ünïcødé" + project = (Path(tmp) / "проект Ünïcødé").resolve() project.mkdir() rc, payload, stderr = run_selftest("-WorkDir", str(project), federation="on") self.assertEqual(rc, 0, stderr) @@ -837,14 +907,21 @@ def test_a_local_profile_collapsed_into_a_disabled_account_leaves_the_menu(self) self.assertEqual(out, "0") def test_federation_on_without_an_engine_fails_closed(self): - rc, payload, stderr = run_selftest(federation="on", env={ - "SAI_ACCOUNTS_EXE": str(REPO / "Scripts" / "consoles" / "ACCOUNTS.ps1")}) - # The canonical install still resolves on this machine, so the honest - # assertion is the one below: 'on' never silently degrades to 'off'. - if payload: - self.assertIsNotNone(payload["federation"]["engine"]) - else: - self.assertIn("control plane is not installed", stderr) + # Inject an absent resolver into a disposable module: a developer's + # deployed/repo-built engine must not turn this negative into success. + with tempfile.TemporaryDirectory(prefix="saituls-no-engine-") as tmp: + root = Path(tmp) + (root / "CONSOLES.ps1").write_text(LAUNCHER_SOURCE, encoding="utf-8-sig") + (root / "ACCOUNTS.ps1").write_text( + ACCOUNTS_SOURCE + "\nfunction Resolve-SaiAccountsEngine { return $null }\n", + encoding="utf-8-sig") + shutil.copy(REGISTRY, root / "consoles.json") + completed = subprocess.run( + ["powershell", "-NoProfile", "-File", str(root / "CONSOLES.ps1"), + "-SelfTest", "-Federation", "on"], capture_output=True, text=True, + encoding="utf-8", errors="replace", env=console_test_environment(), timeout=30) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("control plane is not installed", completed.stdout + completed.stderr) def test_installer_and_launcher_share_one_expansion(self): self.assertIn("ACCOUNTS.ps1", INSTALLER_SOURCE) @@ -1014,9 +1091,7 @@ def ps_single(text): def psraw(script, env=None): """Plain PowerShell, without dot-sourcing the federation module.""" - merged = dict(os.environ) - if env: - merged.update(env) + merged = console_test_environment(env) completed = subprocess.run( ["powershell", "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "[Console]::OutputEncoding=[Text.Encoding]::UTF8; " + script], @@ -1029,7 +1104,7 @@ def psraw(script, env=None): STUB_DIR = [] -def build_stub_engine(name="stub-engine"): +def build_stub_engine(name="stub-engine", stdout_env="STUB_STDOUT"): """A minimal stand-in for an engine or a CLI. It records the argv it was REALLY started with and prints whatever envelope @@ -1082,7 +1157,8 @@ class StubEngine { return code; } } -''', encoding="utf-8") +'''.replace('GetEnvironmentVariable("STUB_STDOUT")', + 'GetEnvironmentVariable("%s")' % stdout_env), encoding="utf-8") built = subprocess.run([csc, "-nologo", "-target:exe", "-out:" + str(exe), str(source)], capture_output=True, text=True, timeout=180) if built.returncode != 0 or not exe.exists(): @@ -1204,7 +1280,7 @@ def setUp(self): self.windir = os.environ.get("WINDIR", r"C:\Windows") def launch(self, *extra, env=None, launcher=None): - merged = dict(os.environ) + merged = console_test_environment() merged["SAITULS_CONSOLE_LOG"] = self.log if env: merged.update(env) @@ -1274,7 +1350,7 @@ def test_a_local_console_launch_is_recorded_as_launched(self): "requires_admin": False, "title_suffix": "Stub", "description": "stub CLI"}] (Path(registry) / "consoles.json").write_text(json.dumps(doc), encoding="utf-8") - project = os.path.join(self.tmp, "project") + project = str((Path(self.tmp) / "project").resolve()) os.makedirs(project, exist_ok=True) argv_file = os.path.join(self.tmp, "argv.txt") completed = self.launch( diff --git a/tests/test_del_junk_all_disks.py b/tests/test_del_junk_all_disks.py index d5e541c..9d91a40 100644 --- a/tests/test_del_junk_all_disks.py +++ b/tests/test_del_junk_all_disks.py @@ -185,7 +185,7 @@ def test_safe_disk_is_the_only_policy(): and '"SAFE_DISK"' in ALL_DISKS_SOURCE) check('the single-target worker still chooses its policy from the target', 'mode = select_policy(target_dir)' in SOURCE - and WORKER.select_policy('V:\\a\\b') == 'AGGRESSIVE_PROJECT') + and WORKER.select_policy(SCRIPTS) == 'AGGRESSIVE_PROJECT') check('the shell all-disks command is recognized, a path is not', WORKER.wants_all_disks(['DEL_JUNK.PYW', '--all-disks']) and not WORKER.wants_all_disks(['DEL_JUNK.PYW', 'G:\\']) diff --git a/tests/test_managed_console_context.py b/tests/test_managed_console_context.py index c153414..73a64e0 100644 --- a/tests/test_managed_console_context.py +++ b/tests/test_managed_console_context.py @@ -543,7 +543,7 @@ def test_autoconnect_lifecycle_and_scope(): def ag_account_local(plane): return {'id': 'antigravity:windows-user:' + plane.sid, 'backend': 'windows_user', 'windows_sid': plane.sid, 'provider': 'antigravity', 'label': 'Antigravity', - 'compact_label': 'AG1', 'windows_user': 'vac34', 'enabled': True} + 'compact_label': 'AG1', 'windows_user': os.environ.get('USERNAME', 'operator'), 'enabled': True} def test_launch_does_not_re_enable_disconnected(): @@ -709,16 +709,33 @@ def test_yolo_current_user_launch(): if not agy: check('yolo13-current-user-launch-carries-yolo', False, 'fake agy.exe did not build') return + fixture_exe = os.path.join(p.dir, 'credential-launch-fixture.exe') + compiled = subprocess.run([ + CSC, '/nologo', '/target:exe', '/main:CredentialProbeFixture', + '/r:System.dll', '/r:System.Core.dll', '/r:System.Web.Extensions.dll', + '/out:' + fixture_exe, ENGINE, + os.path.join(ROOT, 'tests', 'credential_probe_fixture.cs'), + ], capture_output=True, text=True) + check('yolo13-fixture-builds', compiled.returncode == 0, compiled.stdout + compiled.stderr) + if compiled.returncode: + return + p.executable = fixture_exe p.legacy('user', [ag_account_local(p)]) p.run('import') acc_id = p.registry()['accounts'][0]['account_id'] clear_agy_argv(p) + p.env['SAI_FIXTURE_CREDENTIAL_PRESENT'] = '0' + denied_code, denied, _, _ = p.run('launch', acc_id, '--workdir', p.dir) + check('yolo13-authentication-is-required', + denied_code != 0 and denied.get('status') == 'AUTH_REQUIRED' + and not os.path.exists(os.path.join(p.dir, 'bin', 'agy-argv.txt')), str(denied)) + p.env['SAI_FIXTURE_CREDENTIAL_PRESENT'] = '1' code, out, _, _ = p.run('launch', acc_id, '--workdir', p.dir) argv = read_agy_argv(p) check('yolo13-current-user-launch-carries-yolo', code == 0 and out.get('status') == 'launched' and argv is not None - and YOLO_FLAG in argv, (argv or 'no argv')[:300]) + and YOLO_FLAG in argv, (argv or json.dumps(out))[:1000]) check('yolo13b-launch-policy-reported', out.get('launch_policy') == YOLO_FLAG, str(out)[:200]) check('yolo13c-exact-workdir-survives', @@ -1203,9 +1220,11 @@ def input_policy_violations(src, extra_sources=()): # 32. No per-launch consent dialog for the broker, and no new modal in the # Accounts path. + connect_body = re.sub(r'//.*', '', method_body(gui, 'void AccountsContext(')) check('rt32-no-broker-consent-prompt', - not re.search(r'(connect|start).{0,40}(may start|allow the broker|confirm)', gui, re.I) - and 'MessageBox' not in re.sub(r'//.*', '', gui[gui.find('void AccountsContext'):gui.find('void AccountsContext') + 4000]), + bool(connect_body) + and not re.search(r'(connect|start).{0,40}(may start|allow the broker|confirm)', connect_body, re.I) + and 'MessageBox' not in connect_body, 'a consent prompt crept into the connect path') # 33. The sweep is bounded and runs off the UI thread, so startup never blocks diff --git a/tests/test_sai_access.py b/tests/test_sai_access.py index 9666451..0b32d35 100644 --- a/tests/test_sai_access.py +++ b/tests/test_sai_access.py @@ -4,8 +4,8 @@ module is allowed to use (get / probe-workdir / verify-file), and every verb it receives is recorded so the test can prove no privileged verb was ever asked for. icacls runs for real, against disposable objects in a temp directory, under -the operator's own identity: the ACE written and removed is one this lease -created, and nothing else is touched. +the operator's own identity, granting Local Service access to disposable test +objects through a fake registry. No Windows account or session is created. Run: python tests/test_sai_access.py """ @@ -137,7 +137,13 @@ def main(): capture_output=True, text=True).stdout.strip() if not identity.startswith("S-1-5-"): raise SystemExit("could not resolve an operator SID for the ACL checks: %r" % identity) - os.environ["FAKE_IDENTITY"] = identity + # Use a resolvable SID absent from the file's default ACL, so the lease + # cannot merge with (or revoke) the operator's pre-existing FullControl. + os.environ["FAKE_IDENTITY"] = 'S-1-5-19' + target_name = subprocess.run([ + "powershell", "-NoProfile", "-Command", + "([Security.Principal.SecurityIdentifier]'S-1-5-19').Translate([Security.Principal.NTAccount]).Value", + ], capture_output=True, text=True, check=True).stdout.strip() global VERB_LOG VERB_LOG = os.path.join(tmp, "verbs.log") os.environ["FAKE_VERB_LOG"] = VERB_LOG @@ -149,6 +155,9 @@ def main(): target = os.path.join(workdir, "live.log") with open(target, "w", encoding="utf-8") as handle: handle.write("hello\n") + # Freeze this disposable object's inherited baseline before exercising + # leases; hosted temp directories may materialize inherited ACEs lazily. + subprocess.run(["icacls", target, "/inheritance:d"], check=True, capture_output=True) # --- argument and selection refusals for argv, code in ( @@ -205,10 +214,11 @@ def main(): "recorded the wrong result") # icacls prints the account's SID under its resolved name, so the ACE is # identified by the read right this lease granted, not by the SID string. - check("access-grant-adds-read-ace", ":(R)" in after and ":(R)" not in before, + granted = [line for line in after.splitlines() if target_name in line] + check("access-grant-adds-read-ace", len(granted) == 1 and ":(R)" in granted[0], (before, after)) check("access-grant-is-not-modify", - ":(M)" not in after and ":(F)" not in after, after) + all(":(M)" not in line and ":(F)" not in line for line in granted), after) check("access-grant-expiry-set", doc.get("expires_at") and doc.get("expires_at_iso"), doc.get("expires_at_iso")) check("access-grant-caveats-open-handles", "already-open" in doc.get("expiry_caveat", ""), @@ -237,6 +247,34 @@ def main(): check("access-foreign-ace-untouched-by-refusal", access.acl_text(target) == before, "a refused grant still mutated the object") + # A broader existing allow is equally unowned. In particular, /grant R + # must never claim ownership of an existing F and later remove that F. + access.icacls(target, "/grant", os.environ["FAKE_IDENTITY"], "(F)") + broad_before = access.acl_text(target) + rc, doc = grant(["--account", "ag2", "--source", target, "--minutes", "15"]) + check("access-refuses-preexisting-full-control", + rc != 0 and doc.get("status") == "EQUIVALENT_ACE_ALREADY_PRESENT", (rc, doc)) + check("access-preserves-preexisting-full-control", access.acl_text(target) == broad_before, doc) + access.icacls(target, "/remove:g", os.environ["FAKE_IDENTITY"]) + + capture(["grant", "--account", "ag2", "--source", target, "--minutes", "15"]) + access.icacls(target, "/grant", os.environ["FAKE_IDENTITY"], "(F)") + changed = access.acl_text(target) + rc, doc = capture(["revoke", "--account", "ag2", "--source", target]) + check("access-revoke-refuses-concurrent-grant", + rc != 0 and doc.get("status") == "ACL_CHANGED_SINCE_GRANT", (rc, doc)) + check("access-revoke-preserves-concurrent-grant", access.acl_text(target) == changed, doc) + changed_lease = access.read_json(lease_file) + changed_lease["expires_at"] = 1 + access.write_json_atomic(lease_file, changed_lease) + rc, doc = capture(["sweep"]) + check("access-sweep-preserves-concurrent-grant", + access.acl_text(target) == changed and any( + row.get("reason") == "ACL_CHANGED_SINCE_GRANT" for row in doc.get("unrevoked", [])), doc) + # Cleanup only this fixture's rule and this disposable lease. + access.icacls(target, "/remove:g", os.environ["FAKE_IDENTITY"]) + os.remove(lease_file) + # --- rollback mismatch is preserved as evidence, never smoothed over capture(["grant", "--account", "ag2", "--source", target, "--minutes", "60"]) tampered = access.read_json(lease_file) diff --git a/tests/test_sai_accounts.py b/tests/test_sai_accounts.py index 3e550a3..22b1311 100644 --- a/tests/test_sai_accounts.py +++ b/tests/test_sai_accounts.py @@ -75,6 +75,7 @@ class Plane: """One isolated control-plane environment (registry + broker processes).""" def __init__(self, scope='op-test'): + self.executable = EXE self.dir = tempfile.mkdtemp(prefix='sai-accounts-test-') self.scope = scope self.sid = real_sid() @@ -88,7 +89,7 @@ def __init__(self, scope='op-test'): }) def run(self, *args, timeout=90): - r = subprocess.run([EXE] + list(args), capture_output=True, text=True, + r = subprocess.run([self.executable] + list(args), capture_output=True, text=True, env=self.env, timeout=timeout, cwd=self.dir) try: payload = json.loads(r.stdout.strip().splitlines()[-1]) if r.stdout.strip() else None @@ -115,6 +116,26 @@ def legacy(self, which, accounts, schema_version=1): with open(path, 'w', encoding='utf-8') as fh: json.dump({'schema_version': schema_version, 'accounts': accounts}, fh) + def profile(self, provider): + """Seed a profile in this fixture, without relying on operator profiles.""" + path = os.path.join(self.dir, provider + '-profile') + os.makedirs(path, exist_ok=True) + identity = os.path.normpath(path).rstrip('\\').lower() + account_id = provider + ':profile-dir:' + hashlib.sha256(identity.encode('utf-8')).hexdigest()[:16] + doc = self.registry() + doc['accounts'].append({ + 'account_id': account_id, 'provider_id': provider, + 'display_name': None, 'execution_backend': 'profile_directory', + 'execution_context_id': 'current-user', 'operational_state': 'ENABLED', + 'hidden': False, 'auto_connect': False, 'auto_connect_reason': 'default', + 'created_at': '2026-10-01T00:00:00Z', 'updated_at': '2026-10-01T00:00:00Z', + 'provider_metadata': {'profile_locator': path, + 'env_scrub': ['OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_ACCESS_TOKEN']}, + 'tags': [], + }) + self.write_registry(doc) + return account_id + def cleanup(self): shutil.rmtree(self.dir, ignore_errors=True) @@ -713,10 +734,11 @@ def test_profile_directory_launch(): p.legacy('user', [ag_account('S-1-5-21-9-9-9-1002', 'op_a')]) p.run('import') + profile_id = p.profile('codex') _, listing, _, _ = p.run('list') codex = None for a in (listing or {}).get('accounts', []): - if a.get('provider_id') == 'codex' and a.get('execution_backend') == 'profile_directory': + if a.get('account_id') == profile_id: codex = a break check('profile-dir-account-exists', codex is not None, json.dumps(listing)[:200]) @@ -1498,9 +1520,9 @@ def test_auth_operation(): p.run('restore', ids['AG2']) # Only providers with an interactive login can answer. - p.run('add', '--provider', 'claude', '--alias', 'Claude profile') + profile_id = p.profile('claude') _, listing2, _, _ = p.run('list', '--all') - claude = [a for a in listing2['accounts'] if a['provider_id'] != 'antigravity'] + claude = [a for a in listing2['accounts'] if a['account_id'] == profile_id] if claude: code, out, _, _ = p.run('auth', claude[0]['account_id']) check('auth04-non-antigravity-provider-refused', @@ -1749,7 +1771,7 @@ def test_workdir_grants(): rows = ledger(p) check('grant16-ledger-records-what-we-created', len(rows) == 1 and rows[0].get('created') is True - and rows[0].get('workdir', '').rstrip('\\').lower() == os.path.normpath(workdir).rstrip('\\').lower(), + and os.path.normcase(os.path.realpath(rows[0].get('workdir', ''))) == os.path.normcase(os.path.realpath(workdir)), str(rows)[:200]) # (11) the second call is a no-op that claims no ownership. diff --git a/tests/test_saipatch.ps1 b/tests/test_saipatch.ps1 index be96009..dfda520 100644 --- a/tests/test_saipatch.ps1 +++ b/tests/test_saipatch.ps1 @@ -190,6 +190,7 @@ try { $unit = & node --test (Join-Path $patchSrc 'saipatch-native-queue-2x.test.mjs') (Join-Path $patchSrc 'saipatch-completion-sound.test.mjs') 2>&1 $unitOut = (($unit | ForEach-Object { "$_" }) -join "`n") $unitRc = $LASTEXITCODE + if ($unitRc -ne 0) { Write-Host $unitOut } Check '2. plugin unit tests green (projection, queue semantics, ambient, wiring, completion sound)' ($unitRc -eq 0) "exit=$unitRc" $mf = Get-Content -Raw -LiteralPath (Join-Path $patchSrc 'manifest.json') | ConvertFrom-Json diff --git a/tests/test_scenarios_launcher.py b/tests/test_scenarios_launcher.py index a567f34..fce920e 100644 --- a/tests/test_scenarios_launcher.py +++ b/tests/test_scenarios_launcher.py @@ -185,11 +185,16 @@ def probe_path(rel): check("legitimate in-root path accepted", rc == 0 and r and r["ok"]) print("== argument passing (Unicode / spaces / parens / ampersand) ==") +# Quoting is independent of optional scenario packages. Select a shipped +# Python scenario with a target and no dependencies, just as the resolution +# tests do; a clean runner must not need mutagen to inspect an argv plan. +argv_candidate = next(s for s in zds if s["interpreter"] == "python" + and s["target_mode"] in ("file", "folder")) hostile = "C:/tmp/u-ãéïöü-тест (x) & more" -rc, out = run_launcher("-Scenario", "audio.tag-mp3", "-Target", hostile) +rc, out = run_launcher("-Scenario", argv_candidate["id"], "-Target", hostile) r = parse_json_out(out) check("hostile target accepted as single argv element", rc == 0 and r and r["ok"] - and r["argv"][-1] == hostile) + and r["argv"][-1] == hostile, out) check("target arrives exactly once", r and len(r["argv"]) == 2) # CommandLineToArgvW round-trip: assert the TARGET parses back byte-identical # (the script path is re-homed when the repo moves, so compare element 1 only). @@ -197,7 +202,7 @@ def probe_path(rel): target_ok = (parsed is not None and len(parsed) == 2 and parsed[1] == hostile) check("Win32 command line round-trips hostile target", target_ok, f"parsed={parsed}") trail = "C:\\tmp\\trail test\\" -rc, out = run_launcher("-Scenario", "audio.tag-mp3", "-Target", trail) +rc, out = run_launcher("-Scenario", argv_candidate["id"], "-Target", trail) r2 = parse_json_out(out) parsed2 = win32_argv(r2["cmdline"]) check("trailing backslash survives quoting", parsed2 is not None and parsed2[1] == trail, diff --git a/tests/test_secure_apps_hygiene.py b/tests/test_secure_apps_hygiene.py index 54896c9..4265765 100644 --- a/tests/test_secure_apps_hygiene.py +++ b/tests/test_secure_apps_hygiene.py @@ -397,7 +397,9 @@ class ElevatedWorkerLaunchTests(unittest.TestCase): HELPER = SUBSYSTEM / "sa_storage_helper.ps1" def _run_harness(self, helper=None): - scratch = Path(tempfile.mkdtemp(prefix="saituls-worker-launch-")) + # The helper deliberately refuses noncanonical paths. Resolve the live + # fixture once so a TEMP 8.3 alias does not mask later refusal branches. + scratch = Path(tempfile.mkdtemp(prefix="saituls-worker-launch-")).resolve() self.addCleanup(shutil.rmtree, scratch, ignore_errors=True) (scratch / "empty-root").mkdir() runtime = scratch / "privileged" diff --git a/tests/test_secure_apps_privtask.py b/tests/test_secure_apps_privtask.py index 584f712..65ff96b 100644 --- a/tests/test_secure_apps_privtask.py +++ b/tests/test_secure_apps_privtask.py @@ -1584,15 +1584,19 @@ def test_the_task_xml_is_written_in_protected_scratch_not_user_temp(self): real_open = builtins.open def watched(path, *args, **kwargs): + handle = real_open(path, *args, **kwargs) if isinstance(path, str) and path.lower().endswith(".xml"): - seen.append(path) - return real_open(path, *args, **kwargs) + # Measure the live file, before transaction cleanup removes it. + # An existing root can expand an 8.3 alias while a deleted XML + # retains its short spelling, making a later comparison false. + seen.append((path, sa_privtask.path_is_within(self.scratch, path))) + return handle with mock.patch.object(builtins, "open", watched): self.assertTrue(self.install()["ok"]) self.assertTrue(seen, "no task XML was written at all") - for path in seen: - self.assertTrue(sa_privtask.path_is_within(self.scratch, path), + for path, was_within in seen: + self.assertTrue(was_within, "the task XML was written outside protected " "scratch: %s" % path) # ...and in production that scratch root is under %ProgramData%, not diff --git a/tests/test_shell_menu.ps1 b/tests/test_shell_menu.ps1 index eff14d4..23325ee 100644 --- a/tests/test_shell_menu.ps1 +++ b/tests/test_shell_menu.ps1 @@ -2,7 +2,9 @@ param( # The tree whose Registry\*.REG and Scripts\ are under test. Defaults to the # repository this file lives in; point it at an older checkout to use this # same harness as a red control. - [string]$Repo = (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Definition)) + [string]$Repo = (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Definition)), + [string]$WaitImplementation = (Join-Path $PSScriptRoot 'shell_probe_wait.ps1'), + [ValidateRange(0,60000)][int]$RecorderDelayMilliseconds = 0 ) $ErrorActionPreference = 'Stop' @@ -46,12 +48,20 @@ public class SaiShellExec { } [DllImport("shell32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool ShellExecuteExW(ref SHELLEXECUTEINFO lpExecInfo); + [DllImport("kernel32.dll", SetLastError=true)] + public static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds); + [DllImport("kernel32.dll", SetLastError=true)] + public static extern bool GetExitCodeProcess(IntPtr handle, out uint exitCode); + [DllImport("kernel32.dll", SetLastError=true)] + public static extern bool CloseHandle(IntPtr handle); } '@ +. $WaitImplementation $sandbox = Join-Path $env:TEMP ('saituls_menu_' + [Guid]::NewGuid().ToString('N')) -$out = Join-Path $sandbox 'recorded.txt' $fails = 0 +$cleanupReady = $true +$ownedKeys = @() function Check([string]$name, [bool]$ok, [string]$detail = '') { if ($ok) { Write-Host "PASS $name $detail" } else { Write-Host "FAIL $name $detail"; $script:fails++ } @@ -92,10 +102,12 @@ try { Copy-Item $shellArg $sandbox -Force } - # The recorder's argument handling is the workers': shell_target(argv[1]). - $recorder = Join-Path $sandbox 'recorder.pyw' - @" -import os, sys + # Each case owns its script and output: a timed-out recorder must never + # supply a later case's evidence or lose its script while it is still live. + function New-Recorder([string]$recorder, [string]$out) { + @" +import os, sys, time +time.sleep($RecorderDelayMilliseconds / 1000.0) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) try: from shell_arg import shell_target @@ -106,6 +118,7 @@ t = shell_target(sys.argv[1]) open(r'$out', 'w', encoding='utf-8').write( "raw=%r target=%r abspath=%r isdir=%s" % (sys.argv[1], t, os.path.abspath(t), os.path.isdir(t))) "@ | Set-Content -LiteralPath $recorder -Encoding UTF8 + } # DEL_JUNK is the only worker registered on Drive as well as Directory, so it # is the one that exposes the drive-root case. @@ -131,14 +144,18 @@ open(r'$out', 'w', encoding='utf-8').write( ) foreach ($case in $cases) { + $out = Join-Path $sandbox ("recorded-" + $case.class + '.txt') + $recorder = Join-Path $sandbox ("recorder-" + $case.class + '.pyw') + New-Recorder $recorder $out $shipped = Get-ShippedCommand (Join-Path $Repo 'Registry\DEL_JUNK.REG') $case.class $Repo if (-not $shipped) { Check "$($case.class): the .REG declares a command" $false 'no command value found' continue } $probe = $shipped.Replace($worker, $recorder) - $verb = "SaiMenuProbe$($case.class)" + $verb = "SaiMenuProbe$($case.class)_$([Guid]::NewGuid().ToString('N'))" $key = "HKCU:\Software\Classes\$($case.class)\shell\$verb" + $ownedKeys += $key New-Item -Path "$key\command" -Force | Out-Null Set-ItemProperty -Path "$key\command" -Name '(default)' -Value $probe @@ -150,14 +167,15 @@ open(r'$out', 'w', encoding='utf-8').write( $si.lpFile = $case.target $si.nShow = 0 $launched = [SaiShellExec]::ShellExecuteExW([ref]$si) - Start-Sleep -Milliseconds 1200 + $processResult = Wait-SaiShellProbeProcess $si.hProcess + if (-not $processResult.completed) { $cleanupReady = $false } Remove-Item $key -Recurse -Force -ErrorAction SilentlyContinue $launcher = ($probe -split ' ')[0] Check "$($case.label): the shell resolves the shipped launcher $launcher" $launched ` $(if ($launched) { '' } else { "hInstApp=$([int]$si.hInstApp) -- the menu entry cannot start" }) - if (Test-Path $out) { + if ($processResult.completed -and $processResult.exit -eq 0 -and (Test-Path $out)) { $rec = Get-Content $out -Raw $raw = ([regex]::Match($rec, "raw='([^']*)'")).Groups[1].Value.Replace('\\', '\') $target = ([regex]::Match($rec, "target='([^']*)'")).Groups[1].Value.Replace('\\', '\') @@ -174,14 +192,23 @@ open(r'$out', 'w', encoding='utf-8').write( ($target -eq $want -and $abspath -eq $want -and $isdir -eq 'True') ` "raw='$raw' target='$target' abspath='$abspath' isdir=$isdir" } else { - Check "$($case.label): the worker receives the real target" $false 'the worker never ran' + Check "$($case.label): the worker receives the real target" $false ` + "no completed recorder: wait=$($processResult.wait) exit=$($processResult.exit)" } } } finally { - foreach ($c in 'Drive', 'Directory') { - Remove-Item "HKCU:\Software\Classes\$c\shell\SaiMenuProbe$c" -Recurse -Force -ErrorAction SilentlyContinue + foreach ($ownedKey in $ownedKeys) { + Remove-Item -LiteralPath $ownedKey -Recurse -Force -ErrorAction SilentlyContinue + } + if ($cleanupReady) { + $full = [IO.Path]::GetFullPath($sandbox) + $tempBase = [IO.Path]::GetFullPath($env:TEMP).TrimEnd('\') + '\' + if (-not $full.StartsWith($tempBase, [StringComparison]::OrdinalIgnoreCase) -or + (Split-Path $full -Leaf) -notlike 'saituls_menu_*') { throw 'Unsafe recorder cleanup target' } + Remove-Item -LiteralPath $full -Recurse -Force -ErrorAction SilentlyContinue + } else { + Write-Host "Recorder did not complete; retained its owned sandbox: $sandbox" } - Remove-Item -LiteralPath $sandbox -Recurse -Force -ErrorAction SilentlyContinue } Write-Host '---' diff --git a/tests/test_usn_journal_guard.ps1 b/tests/test_usn_journal_guard.ps1 index 515a755..1c82f4e 100644 --- a/tests/test_usn_journal_guard.ps1 +++ b/tests/test_usn_journal_guard.ps1 @@ -132,13 +132,13 @@ function New-Mock { function Step([int]$exit, [string]$output) { return [pscustomobject]@{ exit = $exit; output = $output } } function Invoke-Guard { - param([string]$Mock, [string[]]$Extra = @(), [switch]$ExpectRaw, [string]$RegKey = '', [hashtable]$Replace = @{}, [string]$Volumes = 'C') + param([string]$Mock, [string[]]$Extra = @(), [switch]$ExpectRaw, [string]$RegKey = '', [hashtable]$Replace = @{}, [string]$Volumes = 'C', [string]$Source = $GuardSource) $stamp = [Guid]::NewGuid().ToString('N') $stdout = Join-Path $Sandbox "out_$stamp.txt" $stderr = Join-Path $Sandbox "err_$stamp.txt" $log = Join-Path $Sandbox "guard_$stamp.log" $reg = if ($RegKey) { $RegKey } else { $scratchKey } - $base = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $GuardSource, + $base = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $Source, '-Volume', $Volumes, '-FsutilPath', $Mock, '-RegistryKey', $reg, '-LogPath', $log, '-Json', '-ResizeWaitSeconds', '10', '-ResizePollSeconds', '0') foreach ($k in $Replace.Keys) { @@ -283,6 +283,39 @@ Check 'failed_createjournal_exits_nonzero' ($r.Code -eq 2 -or $r.Code -eq 3) "ex Check 'failed_createjournal_is_reported' ((Get-ProblemText $r.Report) -match 'createjournal failed') "problems=$(Get-ProblemText $r.Report)" Check 'failed_createjournal_does_not_delete' ((@($calls | Where-Object { $_ -match 'deletejournal' }).Count) -eq 0) "calls=[$($calls -join ' / ')]" +# The hosted runner can be elevated even when the local test process is not. +# Exercise both classification branches without elevation or real fsutil: +# only the admin fact in a sandbox copy changes; every operation still uses +# the recording fake and scratch registry key. Otherwise exit 3 on a local +# unelevated host can hide a missing ToolFailed flag (hosted exit 1). +$guardText = [System.IO.File]::ReadAllText($GuardSource) +$adminAssignment = '$script:IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)' +if ([regex]::Matches($guardText, [regex]::Escape($adminAssignment)).Count -ne 1) { + throw 'admin classification fixture must replace exactly one native admin fact' +} +foreach ($adminFact in @($true, $false)) { + $label = if ($adminFact) { 'elevated' } else { 'unelevated' } + $expectedCode = if ($adminFact) { 2 } else { 3 } + $factLiteral = if ($adminFact) { '$true' } else { '$false' } + $fixtureSource = Join-Path $Sandbox ("guard_$label.ps1") + [System.IO.File]::WriteAllText($fixtureSource, + $guardText.Replace($adminAssignment, ('$script:IsAdmin = ' + $factLiteral)), + (New-Object System.Text.UTF8Encoding($true))) + + $mock = New-Mock -Name ("create_fails_$label") -QuerySequence @((Step 0 $english1mb)) -Create (Step 1 'Access is denied.') + $r = Invoke-Guard -Mock $mock -Source $fixtureSource -Extra @('-RepairJournals', '-AllowJournalRecreate', '-RecreateVolume', 'C') + $calls = Get-Calls $mock + Check "failed_createjournal_${label}_exit_class" ($r.Code -eq $expectedCode -and $r.Report -and $r.Report.exitCode -eq $expectedCode -and $r.Report.elevated -eq $adminFact) "exit=$($r.Code) expected=$expectedCode" + Check "failed_createjournal_${label}_no_delete" (@($calls | Where-Object { $_ -match 'deletejournal' }).Count -eq 0 -and @($calls | Where-Object { $_ -match 'createjournal' }).Count -eq 1) "calls=[$($calls -join ' / ')]" + + $mock = New-Mock -Name ("delete_fails_$label") -QuerySequence @((Step 0 $english1mb)) -Delete (Step 1 'Access is denied.') + $r = Invoke-Guard -Mock $mock -Source $fixtureSource -Replace @{ '-ResizeWaitSeconds' = '0' } -Extra @('-RepairJournals', '-AllowJournalRecreate', '-RecreateVolume', 'C') + $calls = Get-Calls $mock + Check "failed_deletejournal_${label}_exit_class" ($r.Code -eq $expectedCode -and $r.Report -and $r.Report.exitCode -eq $expectedCode -and $r.Report.elevated -eq $adminFact) "exit=$($r.Code) expected=$expectedCode" + Check "failed_deletejournal_${label}_reported" ((Get-ProblemText $r.Report) -match 'deletejournal failed') "problems=$(Get-ProblemText $r.Report)" + Check "failed_deletejournal_${label}_no_followup_create" (@($calls | Where-Object { $_ -match 'deletejournal' }).Count -eq 1 -and @($calls | Where-Object { $_ -match 'createjournal' }).Count -eq 1) "calls=[$($calls -join ' / ')]" +} + # ---- 13. registry clamp: read-only by default, removed only on request -- Set-ItemProperty -Path $scratchKey -Name $clampName -Value 1 -Type DWord $mock = New-Mock -Name 'clamp_diagnose' -QuerySequence @((Step 0 $english1mb)) diff --git a/tests/test_workers.py b/tests/test_workers.py index 09b71b9..aaa3426 100644 --- a/tests/test_workers.py +++ b/tests/test_workers.py @@ -21,6 +21,7 @@ filesystem and then answers Yes. That is the real race, executed deterministically. """ import hashlib +import importlib.machinery import importlib.util import json import os