From c30c559bf15e87e138e9b0929fdb2d29fbea8168 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 21 Nov 2026 19:51:19 +0900 Subject: [PATCH 1/2] Revert "fix(windows): query the named task within the stop deadline (#8974)" This reverts commit cc304ef4e7 for the 2.100.8 release. Together with #8931 it makes `ocx service install` fail on a fresh Windows runner: the service-lifecycle windows-schtasks job on dev 067f6231f6 fails twice with "The installed Windows service could not be proven stopped (unknown) ... the process list could not be read", while the same changes passed on top of #9027, which supplies the missing owner evidence. Both return together with #9027 after its review. --- src/service/windows-checked-stop-live.ts | 46 ++------- src/service/windows-process-native.ts | 15 --- structure/ops/windows-checked-stop.md | 7 -- .../windows/windows-checked-stop-live.test.ts | 99 +------------------ 4 files changed, 7 insertions(+), 160 deletions(-) diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index 8b324bbd609..025ac770332 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -42,25 +42,8 @@ import type { WindowsListenerIdentity, WindowsPortSample, WindowsStopConfirmDeps import { windowsSchedulerCsvIncludesTask } from "./windows-scheduler"; import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT, verifyWindowsTaskStopProof } from "./windows-task-instance-stop"; -// Only a missing task after connecting to the local root folder establishes absence. -const TASK_REGISTRATION_SCRIPT = String.raw` -$ErrorActionPreference = 'Stop' -try { - $service = [Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service', $true)) - $service.Connect() - $folder = $service.GetFolder('\') -} catch { 'unknown'; return } -try { - $task = $folder.GetTask('${TASK}') - if ($null -ne $task) { 'present' } else { 'unknown' } -} catch { - if ($_.Exception.GetBaseException().HResult -eq -2147024894) { 'absent' } else { 'unknown' } -}`; - export interface WindowsStopCommandResult { status: number | null; - /** Captured from the spawned process handle. Bun's child exit status can contain only the low byte. */ - windowsExitCode?: number; stdout: string; stderr: string; timedOut: boolean; @@ -110,11 +93,8 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, return; } let file: string; - let native: WindowsProcessNativeApi | null; - let readExitCode: (() => number | null) | null = null; try { file = programPath(program); - native = program === "schtasks" && args.includes("/hresult") ? windowsProcessNative() : null; } catch (error) { resolve({ status: null, stdout: "", stderr: error instanceof Error ? error.message : String(error), timedOut: false }); return; @@ -129,16 +109,13 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, const text = (value: Buffer | string | undefined): string => value === undefined ? "" : typeof value === "string" ? value : decodeWindowsTextBytes(value); const failure = error as (NodeJS.ErrnoException & { killed?: boolean; signal?: string | null; code?: number | string }) | null; - const windowsExitCode = readExitCode?.(); resolve({ status: failure ? (typeof failure.code === "number" ? failure.code : null) : 0, - ...(windowsExitCode == null || failure?.killed ? {} : { windowsExitCode }), stdout: text(stdout), stderr: text(stderr), timedOut: control?.signal?.aborted === true || !!failure?.killed && failure.signal !== null, }); }); - if (helper.pid !== undefined) readExitCode = native?.captureChildExitCode?.(helper.pid) ?? null; if (authorizeProof) { let pending = "", progressLine = "", authorized = false; helper.stdout?.on("data", (chunk: Buffer) => { @@ -325,23 +302,12 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption canonicalPaths: windowsStopCanonicalPaths(), childPid: windowsStopChildPid(), async probeScheduler(timeoutMs) { - const deadline = performance.now() + timeoutMs; - const unknown = { status: "unknown", detail: "the Task Scheduler query did not answer" } as const; - const direct = await run("schtasks", ["/query", "/tn", `\\${TASK}`, "/fo", "CSV", "/nh", "/hresult"], timeoutMs); - if (direct.timedOut || performance.now() >= deadline) return unknown; - if (direct.status === 0 && (direct.windowsExitCode ?? 0) === 0 - && direct.stdout.trimStart().toLowerCase().startsWith(`"\\${TASK}",`)) return { status: "present" }; - if (direct.windowsExitCode !== undefined) { - const missing = 0x80070002; // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) - const statusAgrees = direct.status === 2 || (direct.status !== null && (direct.status >>> 0) === missing); - return direct.windowsExitCode === missing && statusAgrees ? { status: "absent" } : unknown; - } - const remaining = wholeTimeoutMs(deadline - performance.now()); - if (remaining === null) return unknown; - const probe = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", TASK_REGISTRATION_SCRIPT], remaining); - if (probe.timedOut || probe.status !== 0 || performance.now() >= deadline) return unknown; - const status = probe.stdout.trim(); - return status === "present" || status === "absent" ? { status } : unknown; + const started = Date.now(); + const direct = await run("schtasks", ["/query", "/tn", TASK], timeoutMs); + if (direct.status === 0 && direct.stdout.includes(TASK)) return { status: "present" }; + const listing = await run("schtasks", ["/query", "/fo", "CSV"], Math.max(1, timeoutMs - (Date.now() - started))); + if (listing.status !== 0 || listing.timedOut) return { status: "unknown", detail: "the Task Scheduler query did not answer" }; + return windowsSchedulerCsvIncludesTask(listing.stdout, TASK) ? { status: "present" } : { status: "absent" }; }, async probeWinsw(timeoutMs) { // One cap covers both reads: the ownership query gets only what the state query left. diff --git a/src/service/windows-process-native.ts b/src/service/windows-process-native.ts index 301edf24a11..16123c19aff 100644 --- a/src/service/windows-process-native.ts +++ b/src/service/windows-process-native.ts @@ -64,8 +64,6 @@ export type WindowsProcessWatch = | { status: "gone" | "reused" | "denied" | "unavailable" }; export interface WindowsProcessNativeApi { - /** Pin a just-spawned child until its completion callback reads its full Windows exit code. */ - captureChildExitCode?(pid: number): (() => number | null) | null; /** Creation time in epoch ms (FILETIME truncated to ms), or null when unreadable. */ creationTime(pid: number): number | null; /** Creation in .NET ticks at CIM precision from a live process with the same token user. */ @@ -141,7 +139,6 @@ function loadNativeApi(): WindowsProcessNativeApi | null { kernel32 = ffi.dlopen(join(systemDirectory, "kernel32.dll"), { OpenProcess: { args: ["u32", "i32", "u32"], returns: "u64" }, CloseHandle: { args: ["u64"], returns: "i32" }, - GetExitCodeProcess: { args: ["u64", "ptr"], returns: "i32" }, GetProcessTimes: { args: ["u64", "ptr", "ptr", "ptr", "ptr"], returns: "i32" }, TerminateProcess: { args: ["u64", "u32"], returns: "i32" }, WaitForSingleObject: { args: ["u64", "u32"], returns: "u32" }, @@ -202,18 +199,6 @@ function loadNativeApi(): WindowsProcessNativeApi | null { }; nativeApi = { - captureChildExitCode(pid) { - const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); - if (!handle) return null; - return () => { - try { - const code = new Uint32Array(1); - return handleExited(handle) === true && k.GetExitCodeProcess(handle, ptr(code)) ? code[0]! : null; - } finally { - k.CloseHandle(handle); - } - }; - }, creationTime(pid) { const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); if (!handle) return null; diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 48906174f73..e49c11c0785 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -138,13 +138,6 @@ asynchronous `schtasks` and `sc.exe` calls through `execFile` (a deadline-derive floored to whole milliseconds and one that floors to 0 spawns nothing, because `execFile` reads 0 as no timeout), the evidence snapshot `windowsProcessSnapshot` for every bind, the checked terminate, the exit watch, the Part B port sampler and the listener identity. -For Scheduler registration, Part A queries the exact root task with `schtasks /query /tn` and -`/hresult`. On Windows x64 it prepares native exit-code capture during executable lookup, -then reads the full exit code from the spawned process handle. Only -`0x80070002` establishes absence. Bun's truncated process status cannot prove that result. -Where a full exit code is unavailable, the local Scheduler COM API can still confirm the task -or report `ERROR_FILE_NOT_FOUND` from `GetTask` within the remainder of the same 2 s budget. -Denied access, incomplete evidence, and late answers keep the registration unknown. `src/service/windows-task-instance-stop.ts` keeps the root registration and its running instances in one Task Scheduler COM session. It passes the registered XML and the helper's current account as base64 UTF-8 to preserve Unicode through the console. The live adapter checks the recognized task diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index c0fca700b7f..dd53dd279fd 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -23,7 +23,7 @@ import { winswStatusFromScState, windowsCheckedStopLiveDeps, } from "../../src/service/windows-checked-stop-live"; -import { windowsProcessNative, type WindowsProcessNativeApi } from "../../src/service/windows-process-native"; +import type { WindowsProcessNativeApi } from "../../src/service/windows-process-native"; import { windowsLauncherVbsPath } from "../../src/service/state"; import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT } from "../../src/service/windows-task-instance-stop"; import { buildWindowsTaskXml, windowsTaskRegistrationHealthy } from "../../src/service/windows-taskxml"; @@ -272,103 +272,6 @@ describe("capped command answers", () => { const portablePowerShell = Bun.which("pwsh"); -describe("the bounded Scheduler registration query", () => { - test("a direct hit avoids PowerShell; only a completed, exact fallback answer is accepted", async () => { - const directHit = result(0, '"\\opencodex-proxy","N/A","Disabled"'); - const missing = result(1, "", "지정된 파일을 찾을 수 없습니다."); - for (const [direct, fallback, expected] of [ - [directHit, null, "present"], - [{ ...result(2), windowsExitCode: 0x80070002 }, null, "absent"], - [{ ...result(-2147024894), windowsExitCode: 0x80070002 }, null, "absent"], - [{ ...result(1), windowsExitCode: 0x80070002 }, null, "unknown"], - [{ ...result(2), windowsExitCode: 0x80041302 }, null, "unknown"], - [{ ...result(5), windowsExitCode: 0x80070005 }, null, "unknown"], - [{ ...result(null), windowsExitCode: 0x80070002 }, null, "unknown"], - [result(2), result(0, "unknown"), "unknown"], - [result(1, "", "", true), null, "unknown"], - [missing, result(0, "absent\r\n"), "absent"], - [missing, result(0, "present"), "present"], - [missing, result(0, "unknown"), "unknown"], - [missing, result(0, "noise\nabsent"), "unknown"], - [missing, result(1, "absent"), "unknown"], - [missing, result(null, "absent", "", true), "unknown"], - ] as const) { - const calls: string[] = []; - const deps = windowsCheckedStopLiveDeps({ run: async (program, args, timeout) => { - calls.push(program); - if (program === "schtasks") { - expect(args).toEqual(["/query", "/tn", "\\opencodex-proxy", "/fo", "CSV", "/nh", "/hresult"]); - return direct; - } - expect(timeout).toBeGreaterThan(0); - expect(timeout).toBeLessThanOrEqual(2_000); - return fallback!; - } }); - expect((await deps.probeScheduler(2_000)).status).toBe(expected); - expect(calls).toEqual(fallback ? ["schtasks", "powershell"] : ["schtasks"]); - } - }); - - test.skipIf(process.platform !== "win32" || process.arch !== "x64")("the child handle preserves distinct HRESULTs with the same low byte", async () => { - const native = windowsProcessNative(); - expect(native?.captureChildExitCode).toBeFunction(); - for (const code of [0x80070002, 0x80041302]) { - const child = Bun.spawn([resolveTrustedWindowsPowerShellExe(), "-NoProfile", "-NonInteractive", "-Command", - `[Environment]::Exit(${code | 0})`], { stdout: "ignore", stderr: "ignore", windowsHide: true, timeout: SPAWN_BUDGET_MS }); - const readExitCode = native!.captureChildExitCode!(child.pid); - await child.exited; - expect(readExitCode?.()).toBe(code); - } - }, 2 * SPAWN_BUDGET_MS + 1_000); - - test("the fallback uses only the remaining time and a late answer is unknown", async () => { - let now = 100; - const clock = spyOn(performance, "now").mockImplementation(() => now); - try { - const deps = windowsCheckedStopLiveDeps({ run: async (program, _args, timeout) => { - if (program === "schtasks") { now += 750; return result(1); } - expect(timeout).toBe(1_250); - now += timeout; - return result(0, "absent"); - } }); - expect((await deps.probeScheduler(2_000)).status).toBe("unknown"); - } finally { clock.mockRestore(); } - }); - - test.skipIf(process.platform !== "win32" && !portablePowerShell)("only a missing task in an accessible root is absent", async () => { - let script = ""; - await windowsCheckedStopLiveDeps({ run: async (program, args) => { - if (program === "schtasks") return result(1); - script = args.at(-1)!; - return result(0, "unknown"); - } }).probeScheduler(2_000); - const activation = "[Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service', $true))"; - expect(script).toContain(activation); - const fixture = String.raw` -class SchedulerFixture { - [void] Connect() { if ($global:scenario -eq 'connect') { throw [IO.FileNotFoundException]::new() } } - [object] GetFolder([string] $path) { - if ($path -cne '\' -or $global:scenario -eq 'folder') { throw [IO.FileNotFoundException]::new() } - return $this - } - [object] GetTask([string] $name) { - if ($name -cne 'opencodex-proxy') { throw 'wrong name' } - if ($global:scenario -eq 'missing') { throw [Runtime.InteropServices.COMException]::new('missing', -2147024894) } - if ($global:scenario -eq 'denied') { throw [UnauthorizedAccessException]::new() } - if ($global:scenario -eq 'empty') { return $null } - return $this - } -}`; - const command = fixture + "\nforeach ($global:scenario in 'found','missing','denied','connect','folder','empty') { & {\n" - + script.replace(activation, "[SchedulerFixture]::new()") + "\n} }"; - const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!; - const child = Bun.spawn([powershell, "-NoProfile", "-NonInteractive", "-EncodedCommand", - Buffer.from(command, "utf16le").toString("base64")], { stdout: "pipe", stderr: "pipe", windowsHide: true, timeout: SPAWN_BUDGET_MS }); - const [out, err, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); - expect({ code, err, lines: out.trim().split(/\r?\n/) }).toEqual({ code: 0, err: "", lines: ["present", "absent", "unknown", "unknown", "unknown", "unknown"] }); - }, SPAWN_BUDGET_MS + 1_000); -}); - test.skipIf(process.platform !== "win32" && !portablePowerShell)("the PowerShell helper stops captured instances only after every proof succeeds", async () => { const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!; const fixture = String.raw` From 1621d98c7319a721db01a0e0c1f4c163ceee0d8c Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 21 Nov 2026 19:51:19 +0900 Subject: [PATCH 2/2] Revert "fix(service): enforce Windows stop evidence and deadline boundaries (#8931)" This reverts commit 2d71f1406e for the 2.100.8 release; see the previous commit for the Windows service install failure it causes without #9027. --- .../docs/es/reference/cli/lifecycle.md | 11 +- .../content/docs/reference/cli/lifecycle.md | 11 +- scripts/test-layout/layout.json | 2 +- src/service/windows-checked-stop-live.ts | 81 ++--- src/service/windows-checked-stop.ts | 38 +-- src/service/windows-process-evidence.ts | 46 +-- src/service/windows-service-stop.ts | 22 +- src/service/windows-task-instance-stop.ts | 13 +- src/service/windows-taskxml.ts | 17 +- structure/ops/windows-checked-stop.md | 41 +-- tests/fixtures/test-layout-expected.json | 2 +- tests/service/service.test.ts | 4 +- .../windows/windows-checked-stop-live.test.ts | 25 +- .../windows/windows-process-evidence.test.ts | 35 +-- tests/windows/windows-stop-boundary.test.ts | 285 ------------------ 15 files changed, 82 insertions(+), 551 deletions(-) delete mode 100644 tests/windows/windows-stop-boundary.test.ts diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 2b36f1fca34..fe106ad96fc 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -106,16 +106,11 @@ Una salida proxy sola no confirma que la restauración compartida Codex / Grok t En Windows, `ocx stop` detiene una tarea registrada del Programador de tareas o un servicio nativo WinSW mediante una parada verificada. Primero finaliza la tarea y después solo los procesos envoltorios `wscript.exe` y `cmd.exe` que puede vincular a esta instalación (el lanzador o script de servicio de este directorio, una cadena de procesos padres que conduce al proxy o al servicio del Programador de tareas, y una hora de inicio registrada), y espera a que terminen. Solo entonces detiene el proxy de forma controlada. Después confirma que el puerto permanezca libre unos seis segundos y que ningún envoltorio se haya reiniciado, para impedir que un bucle de reinicio vuelva a iniciar el proxy tras una parada exitosa. OpenCodex verifica que la tarea programada inicie esta instalación con tu cuenta de Windows -y comprueba las cuentas de sus desencadenadores y de cada instancia en ejecución antes de detenerla. Una tarea deshabilitada +y comprueba la cuenta de cada instancia en ejecución antes de detenerla. Una tarea deshabilitada de tu cuenta se considera inactiva si no tiene instancias en ejecución. Si hay una tarea en cola, OpenCodex no confirma la parada. Si la comprobación falla, -revisa el lanzador, las cuentas de los desencadenadores y la cuenta de ejecución en el Programador -de tareas. Finalizar sus instancias no repara el registro. Repara un registro que te pertenezca -o contacta con su propietario o administrador. La parada rechaza nuevas acciones al vencer -su límite de tiempo, cancela el proceso auxiliar de parada y conserva los cambios confirmados -en el resultado, incluso si la verificación final sigue pendiente. -Si se envía la autorización y el auxiliar no responde antes del plazo, la CLI indica -que no pudo leer el estado del servicio (`state-unknown`) y marca la parada como fallida. +revisa el lanzador y la cuenta de ejecución en el Programador de tareas y detén la tarea desde +la sesión de esa cuenta. OpenCodex solo finaliza directamente un envoltorio si comprueba que pertenece a tu cuenta. Ignora los envoltorios que pertenecen a otro usuario. Si no puede verificar el propietario diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index fdd60495bfe..0f2b567aea4 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -180,15 +180,10 @@ for about six seconds and that no wrapper started again, so a wrapper's restart the proxy back behind a successful stop. OpenCodex verifies that the scheduled task launches this installation under your Windows account -and checks the account for its triggers and each running instance before stopping it. An owned, disabled task with +and checks the account for each running instance before stopping it. An owned, disabled task with no running instances counts as idle. A queued task prevents OpenCodex from confirming the stop. -If verification fails, check the launcher, trigger accounts and run-as account in Task Scheduler. -Ending its running instances does not repair its registration. Repair a registration you own, -or contact its owner or administrator. The stop refuses further actions once its time limit has -passed, cancels the owned stop helper, and retains confirmed changes in its result even if -final verification is still pending when the time limit expires. -If the helper has not answered by the deadline after approval was sent, the CLI reports that -it could not read the service state (`state-unknown`) and marks the stop as failed. +If verification fails, check the launcher and run-as account in Task Scheduler and stop the task +from its owning session. OpenCodex terminates a wrapper directly only after verifying that it belongs to your account. It ignores wrappers proven to belong to another user. If it cannot verify the owner of a wrapper diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 9560e77348e..e628edbe4fb 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1933,7 +1933,7 @@ "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", - "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-boundary.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", + "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", "windows-process-priority.test.ts": "windows", "windows-scheduler-errors.test.ts": "windows", "windows-scheduler-install-verification.test.ts": "windows", "windows-lifecycle-root-acl.test.ts": "windows", diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index 025ac770332..3051591e138 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -29,7 +29,7 @@ import { parseListenPidsFromNetstat, type ListenPidScan } from "../server/port-r import { dropWindowsTcpRowsForLocalPort } from "../server/windows-tcp-drop"; import { TASK, windowsLauncherVbsPath, windowsServiceScriptPath } from "./state"; import { ancestorWrapperPids } from "./windows-guarded-manager"; -import type { WindowsCheckedStopDeps, WindowsTaskEndResult, WindowsWinswScmState, WindowsWinswStopResult } from "./windows-checked-stop"; +import type { WindowsCheckedStopDeps, WindowsWinswScmState, WindowsWinswStopResult } from "./windows-checked-stop"; import { openWindowsProcessWatch, readScheduleServicePid, @@ -49,21 +49,12 @@ export interface WindowsStopCommandResult { timedOut: boolean; } -export interface WindowsStopCommandControl { - remainingMs?: () => number; - signal?: AbortSignal; - /** Approval was dispatched; a cap cannot assume no mutation before the helper answers. */ - onDispatch?: () => void; - onMutation?: () => void; -} - /** One spawned helper; tests inject it, production runs execFile with a hard timeout. */ export type WindowsStopCommandRunner = ( program: "schtasks" | "sc" | "powershell", args: string[], timeoutMs: number, authorizeProof?: (line: string) => boolean | Promise, - control?: WindowsStopCommandControl, ) => Promise; function programPath(program: "schtasks" | "sc" | "powershell"): string { @@ -74,12 +65,11 @@ function programPath(program: "schtasks" | "sc" | "powershell"): string { return file; } -export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, args, timeoutMs, authorizeProof, control) => new Promise(resolve => { +export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, args, timeoutMs, authorizeProof) => new Promise(resolve => { // execFile reads a 0 timeout as "no timeout": a deadline-derived fraction is floored, and a // timeout that floors to 0 spawns nothing. - const timeout = Math.floor(Math.min(timeoutMs, control?.remainingMs?.() ?? Infinity)); - const deadline = performance.now() + timeout; - if (!(timeout > 0) || control?.signal?.aborted) { + const timeout = Math.floor(timeoutMs); + if (!(timeout > 0)) { resolve({ status: null, stdout: "", stderr: "", timedOut: true }); return; } @@ -99,12 +89,7 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, resolve({ status: null, stdout: "", stderr: error instanceof Error ? error.message : String(error), timedOut: false }); return; } - const spawnTimeout = Math.floor(Math.min(deadline - performance.now(), control?.remainingMs?.() ?? Infinity)); - if (!(spawnTimeout > 0) || control?.signal?.aborted) { - resolve({ status: null, stdout: "", stderr: "", timedOut: true }); - return; - } - const helper = execFile(file, args, { encoding: "buffer", timeout: spawnTimeout, windowsHide: true, maxBuffer: 1024 * 1024, signal: control?.signal }, + const helper = execFile(file, args, { encoding: "buffer", timeout, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => { const text = (value: Buffer | string | undefined): string => value === undefined ? "" : typeof value === "string" ? value : decodeWindowsTextBytes(value); @@ -113,38 +98,21 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, status: failure ? (typeof failure.code === "number" ? failure.code : null) : 0, stdout: text(stdout), stderr: text(stderr), - timedOut: control?.signal?.aborted === true || !!failure?.killed && failure.signal !== null, + timedOut: !!failure?.killed && failure.signal !== null, }); }); if (authorizeProof) { - let pending = "", progressLine = "", authorized = false; - helper.stdout?.on("data", (chunk: Buffer) => { - progressLine += chunk.toString("latin1"); - let end: number; - while ((end = progressLine.indexOf("\n")) >= 0) { - const line = progressLine.slice(0, end).replace(/\r$/, ""); - progressLine = progressLine.slice(end + 1); - if (authorized && line === "stop-attempted") control?.onMutation?.(); - } - }); + let pending = ""; const onProof = async (chunk: Buffer): Promise => { pending += chunk.toString("latin1"); const end = pending.indexOf("\n"); if (end < 0) return; - const proofReceivedAt = performance.now(); helper.stdout?.off("data", onProof); let approved = false; try { approved = await authorizeProof(pending.slice(0, end).replace(/\r$/, "")); } catch { /* An authorizer failure leaves stdin unapproved. */ } - const now = performance.now(); - const remaining = Math.floor(Math.min(deadline - now, control?.remainingMs?.() ?? Infinity)); - authorized = approved && remaining > 0 && control?.signal?.aborted !== true; - // The helper started its stopwatch before sending proof. Measuring from receipt here - // gives it a conservative cutoff on that clock, even if our reply sits unread. - const stopBeforeMs = Math.floor(now - proofReceivedAt + remaining); - if (authorized && helper.stdin && !helper.stdin.destroyed && !helper.stdin.writableEnded) control?.onDispatch?.(); - helper.stdin?.end(authorized ? `stop-before ${stopBeforeMs}\n` : "\n"); + helper.stdin?.end(approved ? "stop\n" : "\n"); }; helper.stdin?.on("error", () => { /* execFile reports the helper's exit or timeout. */ }); helper.stdout?.on("data", onProof); @@ -257,9 +225,6 @@ export interface WindowsCheckedStopLiveOptions { scQcRun?: (timeoutMs: number) => Promise; /** The outer cap, checked before a manager stop and again after Scheduler proof. */ gate?: () => boolean; - /** Share the outer monotonic deadline and cancellation with manager helpers. */ - remainingMs?: () => number; - signal?: AbortSignal; snapshot?: (timeoutMs: number) => Promise; } @@ -329,15 +294,13 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption const whole = wholeTimeoutMs(timeoutMs); return whole === null ? null : readScheduleServicePid({ timeoutMs: whole }); }, - async endTask(timeoutMs, authorize, mutation) { - const finish = (verdict: WindowsTaskEndResult, attempted: boolean) => { mutation?.(attempted, false); return verdict; }; - timeoutMs = Math.min(timeoutMs, options.remainingMs?.() ?? Infinity); - if (!gate() || !(timeoutMs >= 1) || options.signal?.aborted) return finish("failed", false); + async endTask(timeoutMs, authorize) { + if (!gate()) return "failed"; const deadline = performance.now() + Math.floor(timeoutMs); const withinDeadline = () => performance.now() < deadline && gate(); const launcher = windowsLauncherVbsPath(); const script = Buffer.from(WINDOWS_TASK_INSTANCE_STOP_SCRIPT, "utf16le").toString("base64"); - let approved = false, dispatched = false, observedMutation = false; + let approved = false; let refusal: { cause: unknown } | undefined; const ended = await run("powershell", ["-NoProfile", "-NoLogo", "-NonInteractive", "-EncodedCommand", script], timeoutMs, async line => { @@ -350,18 +313,13 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption } approved = withinDeadline(); return approved; - }, { remainingMs: options.remainingMs, signal: options.signal, onDispatch: () => { dispatched = true; mutation?.(false, true); }, onMutation: () => { - observedMutation = true; - mutation?.(true, false); - } }); + }); if (refusal) throw refusal.cause; - const lines = ended.stdout.trim().split(/\r?\n/); - const attempted = observedMutation || lines.includes("stop-attempted"); - if (ended.timedOut || ended.status !== 0) return finish("failed", attempted || dispatched); - const verdict = lines.at(-1); - if (verdict === "unverified-registration" || verdict === "denied") return finish(verdict, attempted); - if (approved && (verdict === "ended" || verdict === "not-running")) return finish(verdict, attempted || verdict === "ended"); - return finish("failed", attempted || dispatched && verdict !== "failed"); + if (ended.timedOut || ended.status !== 0) return "failed"; + const verdict = ended.stdout.trim().split(/\r?\n/).at(-1); + if (verdict === "unverified-registration" || verdict === "denied") return verdict; + if (approved && (verdict === "ended" || verdict === "not-running")) return verdict; + return "failed"; }, async taskState(timeoutMs) { const started = Date.now(); @@ -380,8 +338,7 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption }, async winswStop(timeoutMs) { if (!gate()) return "failed"; - return classifyScStop(await run("sc", ["stop", WINSW_SERVICE_ID], timeoutMs, undefined, - { remainingMs: options.remainingMs, signal: options.signal })); + return classifyScStop(await run("sc", ["stop", WINSW_SERVICE_ID], timeoutMs)); }, winswState: scQuery, proxyAlive: () => { @@ -389,7 +346,7 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption return pid === null ? false : isProcessAlive(pid); }, openWatch: (pid, startTime) => openWindowsProcessWatch(pid, startTime), - terminate: (pid, startTime, timeoutMs) => gate() ? windowsStopTerminate(pid, startTime, timeoutMs) : { status: "unavailable" }, + terminate: (pid, startTime, timeoutMs) => windowsStopTerminate(pid, startTime, timeoutMs), }; } diff --git a/src/service/windows-checked-stop.ts b/src/service/windows-checked-stop.ts index 9a2b0fa92f9..1f57e893f09 100644 --- a/src/service/windows-checked-stop.ts +++ b/src/service/windows-checked-stop.ts @@ -75,8 +75,8 @@ export interface WindowsCheckedStopDeps { probeWinsw(timeoutMs: number): MaybePromise; enumerate(timeoutMs: number): MaybePromise; scheduleServicePid(timeoutMs: number): MaybePromise; - /** Reauthorize after proof; report mutation evidence separately from the final verdict. */ - endTask(timeoutMs: number, authorize?: () => MaybePromise, mutation?: (attempted: boolean, pending?: boolean) => void): MaybePromise; + /** Reauthorize after the Scheduler proof and before releasing the instance stop. */ + endTask(timeoutMs: number, authorize?: () => MaybePromise): MaybePromise; /** Running state of the task (schtasks /query); the final manager-state read. */ taskState(timeoutMs: number): MaybePromise<"running" | "not-running" | "unknown">; winswStop(timeoutMs: number): MaybePromise; @@ -101,8 +101,6 @@ export interface WindowsCheckedStopOptions { admission?: WindowsStopAdmission; /** Throws to refuse. Also runs after Scheduler proof, before the helper can stop any instance. */ authorize?: () => MaybePromise; - /** Detached progress for an outer cap that must return before verification completes. */ - onProgress?: (result: WindowsCheckedStopResult) => void; } export interface WindowsCheckedStopResult { @@ -120,12 +118,6 @@ export interface WindowsCheckedStopResult { budget?: { requiredMs: number; remainingMs: number }; } -export function snapshotWindowsCheckedStopResult(result: WindowsCheckedStopResult): WindowsCheckedStopResult { - return { ...result, registration: { ...result.registration }, bound: result.bound.map(wrapper => ({ ...wrapper })), - unbound: [...result.unbound], terminated: [...result.terminated], - ...(result.budget ? { budget: { ...result.budget } } : {}) }; -} - /** The authorizer refused; partial says what had already happened. */ export class WindowsCheckedStopRefusedError extends Error { constructor(readonly partial: WindowsCheckedStopResult, options: { cause: unknown }) { @@ -179,17 +171,10 @@ export async function stopWindowsServiceChecked( registration: { scheduler: "unknown", winsw: "unknown" }, bound: [], unbound: [], terminated: [], changed: false, }; - let pendingManagerMutation = false; - const publish = () => { - const snapshot = snapshotWindowsCheckedStopResult(result); - snapshot.changed ||= pendingManagerMutation; - options.onProgress?.(snapshot); - }; const finish = (outcome: WindowsCheckedStopOutcome, reason: WindowsStopReason | null, detail: string) => { result.outcome = outcome; result.reason = reason; result.detail = detail; - publish(); return result; }; const authorize = async (): Promise => { @@ -212,7 +197,6 @@ export async function stopWindowsServiceChecked( scheduler: scheduler.ok && scheduler.value.status !== "unknown" ? scheduler.value.status : "unknown", winsw: winsw.ok ? winsw.value : "unknown", }; - publish(); if (result.registration.scheduler === "unknown" || result.registration.winsw === "unknown") { return finish("unknown", "evidence-unreadable", "the service registration could not be read"); } @@ -313,7 +297,6 @@ export async function stopWindowsServiceChecked( targets.push(wrapper); } result.bound = targets; - publish(); const unboundWatches = new Map(); for (const entry of binding?.unbound ?? []) { if (entry.startTime === null) continue; @@ -326,21 +309,13 @@ export async function stopWindowsServiceChecked( if (taskRegistered) { // Check before launching the helper, then again at its mutation boundary. await authorize(); - let mutationKnown = false; const ended = await runCapped(clock, C.taskEnd, - timeoutMs => deps.endTask(timeoutMs, options.authorize ? authorize : undefined, (attempted, pending = false) => { - mutationKnown = true; - pendingManagerMutation = pending; - result.changed ||= attempted; - publish(); - })); + timeoutMs => deps.endTask(timeoutMs, options.authorize ? authorize : undefined)); if (ended.ok && ended.value === "unverified-registration") { return finish("unknown", "evidence-unreadable", - "the scheduled task's launcher, run-as account, or running instances could not be verified for this installation and Windows account. Ending its running instances does not repair its registration. Confirm it in Task Scheduler; repair a registration you own, or contact its owner or administrator"); + "the scheduled task's launcher, run-as account, or running instances could not be verified for this installation and Windows account. Confirm them in Task Scheduler and stop the task from its owning Windows session"); } - if (!mutationKnown) result.changed ||= !ended.ok || ended.value !== "not-running"; - if (!ended.ok) result.changed ||= pendingManagerMutation; - publish(); + result.changed = !ended.ok || ended.value !== "not-running"; if (!ended.ok) return finish("unknown", "evidence-unreadable", "the task end command did not answer within its cap"); if (ended.value === "denied") return finish("denied", "access-denied", "ending the task was denied"); if (ended.value === "failed") return finish("unknown", "evidence-unreadable", "the task end command failed"); @@ -348,7 +323,6 @@ export async function stopWindowsServiceChecked( if (winswStarted) { await authorize(); result.changed = true; - publish(); const stop = await runCapped(clock, C.winswStopCommand, deps.winswStop); if (!stop.ok) return finish("unknown", "evidence-unreadable", "the native service stop did not answer within its cap"); if (stop.value === "denied") return finish("denied", "access-denied", "stopping the native service was denied"); @@ -375,7 +349,6 @@ export async function stopWindowsServiceChecked( } await authorize(); result.changed = true; - publish(); const outcome = await runCapped(clock, windowEnd - clock.now(), timeoutMs => deps.terminate(wrapper.pid, wrapper.startTime, timeoutMs)); if (!outcome.ok) return finish("unknown", "evidence-unreadable", "terminating a bound wrapper did not answer within its cap"); @@ -388,7 +361,6 @@ export async function stopWindowsServiceChecked( } if (status === "terminated") { result.terminated.push(wrapper.pid); - publish(); if (outcome.value.exited === true) exited.set(wrapper.pid, true); } else { // gone, or reused: the bound process no longer exists either way, and a reused PID diff --git a/src/service/windows-process-evidence.ts b/src/service/windows-process-evidence.ts index 312291f2e8d..1a3dbf0ae34 100644 --- a/src/service/windows-process-evidence.ts +++ b/src/service/windows-process-evidence.ts @@ -36,11 +36,9 @@ export interface WindowsEvidenceCommand { args: string[]; timeoutMs: number; maxBufferBytes: number; - /** Snapshot framing can preserve a complete table if later optional enrichment fails. */ - allowPartialOutput?: boolean; } -/** Runs a command; only framed snapshots may retain stdout after a later command failure. */ +/** Runs a command and resolves stdout; rejects on a nonzero exit, a timeout or overflow. */ export type WindowsEvidenceRunner = (command: WindowsEvidenceCommand) => Promise; export interface WindowsEvidenceOptions { @@ -83,7 +81,7 @@ const defaultRunner: WindowsEvidenceRunner = command => new Promise((resolve, re maxBuffer: command.maxBufferBytes, windowsHide: true, }, (error, stdout) => { - if (error && (!command.allowPartialOutput || !stdout.startsWith("OCX_PROCESS_SNAPSHOT "))) reject(error); + if (error) reject(error); else resolve(stdout); }); }); @@ -99,9 +97,11 @@ function powershellArgs(script: string): string[] { } /** - * Owner enrichment admits at most 32 candidates within 1.5 s including enumeration; - * individual CIM calls have a 1 s cap. A complete baseline precedes optional owner reads. - * The earlier cutoff from the helper's process start also accounts for cold PowerShell startup. + * Owner enrichment admits at most 32 candidates within 1.5 s; individual CIM calls also + * have a 1 s operation cap. Unqueried owners stay unknown and every process row survives. + * No owner read starts later than `timeoutMs - SNAPSHOT_OWNER_RESERVE_MS` after the helper + * process started: a cold PowerShell start and first CIM query can use most of the cap on + * a hosted runner, and the 1.5 s loop budget alone did not count that time. * Owner reads prioritize this home's complete launcher/script tokens before other possible * wrapper candidates. A fresh CIM read after GetOwnerSid binds that owner to the original * creation time; a reused PID cannot prove a foreign owner. @@ -114,21 +114,15 @@ export function windowsProcessSnapshotScript(timeoutMs: number): string { .map(path => Buffer.from(path, "utf8").toString("base64")); return [ "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);", - "$ownerBudget = @{ Remaining = 32; Clock = [Diagnostics.Stopwatch]::StartNew();", - " Until = [Diagnostics.Process]::GetCurrentProcess().StartTime.ToUniversalTime().AddMilliseconds(" + ownerCutoffMs + ") };", "$currentSid = $null; try { $currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value } catch { $currentSid = $null };", "$tokens = @('" + paths.join("','") + "') | ForEach-Object { [regex]::Escape([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($_))) };", "$homePath = '(?:^|[\\s\\x22\\x27])(?:' + ($tokens -join '|') + ')(?=$|[\\s\\x22\\x27])';", "$rows = @(Get-CimInstance Win32_Process -ErrorAction Stop);", - "function Write-ProcessSnapshot($owners) {", - " $projected = @($rows | Select-Object ProcessId,ParentProcessId,Name,CommandLine,", - " @{Name='CreationDate';Expression={ if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null } }},", - " @{Name='CurrentUserSid';Expression={ $currentSid }}, @{Name='Owner';Expression={ $owners[$_.ProcessId] }});", - " 'OCX_PROCESS_SNAPSHOT ' + (ConvertTo-Json -InputObject $projected -Depth 3 -Compress) };", - "Write-ProcessSnapshot @{}; [Console]::Out.Flush();", "$priority = @($rows | Where-Object { $_.CommandLine -match $homePath });", "$fallback = @($rows | Where-Object { $_.CommandLine -notmatch $homePath -and", " (($_.Name -match '^(wscript|cscript|cmd)\\.exe$') -or (-not $_.Name) -or ($_.CommandLine -like '*opencodex-service*')) });", + "$ownerBudget = @{ Remaining = 32; Clock = [Diagnostics.Stopwatch]::StartNew();", + " Until = [Diagnostics.Process]::GetCurrentProcess().StartTime.ToUniversalTime().AddMilliseconds(" + ownerCutoffMs + ") };", "$owners = @{};", "foreach ($process in ($priority + $fallback)) {", " if (!$currentSid -or $ownerBudget.Remaining -le 0 -or $ownerBudget.Clock.ElapsedMilliseconds -ge 1500", @@ -138,12 +132,14 @@ export function windowsProcessSnapshotScript(timeoutMs: number): string { " $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 1 -ErrorAction Stop;", " if ($ownerBudget.Clock.ElapsedMilliseconds -ge 1500 -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };", " $after = Get-CimInstance -InputObject $process -OperationTimeoutSec 1 -ErrorAction Stop;", - " if ($ownerBudget.Clock.ElapsedMilliseconds -ge 1500 -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };", " $owners[$process.ProcessId] = @{ Sid = $owner.Sid; ReturnValue = $owner.ReturnValue;", " CreationDate = if ($after.CreationDate) { $after.CreationDate.ToUniversalTime().ToString('o') } else { $null } };", " } catch { continue }", "};", - "Write-ProcessSnapshot $owners", + "$rows | Select-Object ProcessId,ParentProcessId,Name,CommandLine,", + "@{Name='CreationDate';Expression={ if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null } }},", + "@{Name='CurrentUserSid';Expression={ $currentSid }},", + "@{Name='Owner';Expression={ $owners[$_.ProcessId] }} | ConvertTo-Json -Depth 3 -Compress", ].join(" "); } @@ -169,21 +165,8 @@ function foreignProcessOwner(record: Record, startTime: number /** Parse the snapshot JSON. Unparseable output is null: an unread table proves nothing. */ export function parseWindowsProcessSnapshot(output: string): WindowsStopProcessEntry[] | null { - let trimmed = output.trim(); + const trimmed = output.trim(); if (!trimmed) return []; - const prefix = "OCX_PROCESS_SNAPSHOT "; - if (trimmed.startsWith(prefix)) { - const frames = trimmed.split(/\r?\n/).filter(line => line.startsWith(prefix)); - let complete: string | undefined; - for (const frame of frames.reverse()) { - try { - const candidate = frame.slice(prefix.length); - if (Array.isArray(JSON.parse(candidate))) { complete = candidate; break; } - } catch { /* incomplete enrichment */ } - } - if (complete === undefined) return null; - trimmed = complete; - } let parsed: unknown; try { parsed = JSON.parse(trimmed); @@ -244,7 +227,6 @@ export async function windowsProcessSnapshot(options: WindowsEvidenceOptions): P args: powershellArgs(windowsProcessSnapshotScript(options.timeoutMs)), timeoutMs: options.timeoutMs, maxBufferBytes: SNAPSHOT_MAX_BUFFER, - allowPartialOutput: true, })); } catch { return null; diff --git a/src/service/windows-service-stop.ts b/src/service/windows-service-stop.ts index 58d656469bd..6510666f26c 100644 --- a/src/service/windows-service-stop.ts +++ b/src/service/windows-service-stop.ts @@ -21,7 +21,7 @@ import type { PendingTeardownPartA } from "../config/pending-teardown"; import { readRuntimePort } from "../config/process-state"; import type { WinswStatus } from "../lib/winsw"; import type { ServiceStopOutcome } from "./orchestration"; -import { guardedStopWindowsServiceChecked, snapshotWindowsCheckedStopResult, stopWindowsServiceChecked, WindowsCheckedStopRefusedError, windowsStopClock, type WindowsCheckedStopDeps, type WindowsCheckedStopOptions, type WindowsCheckedStopResult, type WindowsStopAdmission, type WindowsStopReason } from "./windows-checked-stop"; +import { guardedStopWindowsServiceChecked, stopWindowsServiceChecked, WindowsCheckedStopRefusedError, windowsStopClock, type WindowsCheckedStopDeps, type WindowsCheckedStopOptions, type WindowsCheckedStopResult, type WindowsStopAdmission, type WindowsStopReason } from "./windows-checked-stop"; import { stopperUnderHomeWrapper, windowsCheckedStopLiveDeps, windowsStopConfirmLiveDeps, type WindowsCheckedStopLiveOptions } from "./windows-checked-stop-live"; import { windowsListenPort } from "./windows-ops"; import type { WindowsStopProcessEntry } from "./windows-process-evidence"; @@ -124,20 +124,16 @@ export const UNDER_OWN_WRAPPER_DETAIL = "this stop runs under this home's servic /** Part A with the live dependencies (or the test hook), optionally capped. */ export async function runWindowsServiceStopPartA(request: WindowsPartARequest = {}): Promise { const deadline = request.capMs === undefined ? Infinity : performance.now() + request.capMs; - const cancellation = new AbortController(); - const remainingMs = () => Math.max(0, deadline - performance.now()); let expired = false; - const withinCap = () => !expired && !cancellation.signal.aborted && remainingMs() > 0; - let progress: WindowsCheckedStopResult | undefined; + const withinCap = () => !expired && performance.now() < deadline; let underOwnWrapper = false; const options: WindowsCheckedStopOptions = { ...(request.admission ? { admission: request.admission } : {}), ...(request.bindSnapshot ? { bindSnapshot: request.bindSnapshot } : {}), - onProgress: result => { progress = result; }, }; const run = async (): Promise => { if (hooks?.partA) return hooks.partA(request); - const live: WindowsCheckedStopLiveOptions = { gate: withinCap, remainingMs, signal: cancellation.signal }; + const live: WindowsCheckedStopLiveOptions = { gate: withinCap }; const base = (hooks?.liveDeps ?? windowsCheckedStopLiveDeps)(live); const selfPid = base.selfPid ?? process.pid; const guard = (table: readonly WindowsStopProcessEntry[] | null): boolean => @@ -158,7 +154,6 @@ export async function runWindowsServiceStopPartA(request: WindowsPartARequest = const authorize = async (): Promise => { if (!withinCap()) throw new Error("the checked stop's cap has passed"); await request.authorize?.(); - if (!withinCap()) throw new Error("the checked stop's cap has passed"); }; const result = await (request.authorize || request.capMs !== undefined ? guardedStopWindowsServiceChecked(authorize, deps, options) @@ -175,28 +170,23 @@ export async function runWindowsServiceStopPartA(request: WindowsPartARequest = } return result; }; - if (request.capMs === undefined) return run().finally(() => cancellation.abort()); + if (request.capMs === undefined) return run(); const work = run().catch(error => { - if (error instanceof WindowsCheckedStopRefusedError && (!request.authorize || !withinCap())) return error.partial; + if (!request.authorize && error instanceof WindowsCheckedStopRefusedError) return error.partial; throw error; }); let timer: ReturnType | undefined; const cap = new Promise(resolve => { timer = setTimeout(() => { expired = true; - cancellation.abort(); resolve(null); }, Math.ceil(deadline - performance.now())); }); try { const result = await Promise.race([work, cap]); - if (result !== null && withinCap()) return result; - const refusal = unknownResult("the checked stop did not finish within its cap"); - return { ...snapshotWindowsCheckedStopResult(result ?? progress ?? refusal), - outcome: refusal.outcome, reason: refusal.reason, detail: refusal.detail }; + return result !== null && withinCap() ? result : unknownResult("the checked stop did not finish within its cap"); } finally { if (timer) clearTimeout(timer); - cancellation.abort(); } } diff --git a/src/service/windows-task-instance-stop.ts b/src/service/windows-task-instance-stop.ts index 446c4f46da6..73522f061aa 100644 --- a/src/service/windows-task-instance-stop.ts +++ b/src/service/windows-task-instance-stop.ts @@ -51,12 +51,8 @@ try { $proof = Microsoft.PowerShell.Utility\ConvertTo-Json -Compress -InputObject @{ xml = $xml; sid = $sid; name = $account } $utf8 = [Text.UTF8Encoding]::new($false, $true) - $stopClock = [Diagnostics.Stopwatch]::StartNew() [Console]::WriteLine([Convert]::ToBase64String($utf8.GetBytes($proof))) - $approval = [Console]::ReadLine() - if ($approval -cnotmatch '^stop-before ([1-9][0-9]{0,8})$') { 'unverified-registration'; return } - $stopBeforeMs = [int]$Matches[1] - if ($stopClock.ElapsedMilliseconds -ge $stopBeforeMs) { 'failed'; return } + if ([Console]::ReadLine() -cne 'stop') { 'unverified-registration'; return } # Resolve the path afresh only to detect a changed registration. It is never a stop target. $current = $folder.GetTask($name) @@ -67,7 +63,6 @@ try { return } foreach ($target in $verified) { - if ($stopClock.ElapsedMilliseconds -ge $stopBeforeMs) { 'failed'; return } $target.Instance.Refresh() if ([Guid]$target.Instance.InstanceGuid -ne $target.Id -or $target.Instance.EnginePID -ne $target.EnginePid -or $target.Instance.State -ne 4) { @@ -75,12 +70,8 @@ try { } } foreach ($target in $verified) { - if ($stopClock.ElapsedMilliseconds -ge $stopBeforeMs) { 'failed'; return } $attempted = $true - try { $target.Instance.Stop() } finally { - [Console]::WriteLine('stop-attempted') - [Console]::Out.Flush() - } + $target.Instance.Stop() } 'ended' } catch { diff --git a/src/service/windows-taskxml.ts b/src/service/windows-taskxml.ts index 25752a5bf33..f4bac8f3ee1 100644 --- a/src/service/windows-taskxml.ts +++ b/src/service/windows-taskxml.ts @@ -514,10 +514,7 @@ export function windowsTaskHasSessionRecoveryTriggers( expectedUserId: ExpectedWindowsTaskUserId | undefined, ): boolean { const scoped = triggers.match(/]*)?>[\s\S]*?<\/SessionStateChangeTrigger>/gi) ?? []; - return !taskXmlHasPrefixedTag(triggers, "SessionStateChangeTrigger") - && scoped.length === taskXmlElementCount(triggers, "SessionStateChangeTrigger") - && scoped.every(element => windowsTaskUserIdMatches(element, expectedUserId)) - && WINDOWS_SESSION_RECOVERY_STATE_CHANGES.every(stateChange => + return WINDOWS_SESSION_RECOVERY_STATE_CHANGES.every(stateChange => scoped.some(element => taskXmlDecodedValueEquals(element, "StateChange", stateChange) && taskXmlOptionalValueEquals(element, "Enabled", "true") @@ -565,13 +562,6 @@ function windowsTaskUserIdMatches( return expectedValues.some(value => taskXmlDecodedValueEquals(element, "UserId", value)); } -function windowsTaskLogonScopeMatches(triggers: string, expectedUserId: ExpectedWindowsTaskUserId | undefined, legacy = false): boolean { - if (taskXmlHasPrefixedTag(triggers, "LogonTrigger") || taskXmlElementCount(triggers, "LogonTrigger") !== 1) return false; - const logon = taskXmlSection(triggers, "LogonTrigger"); - if (legacy && !taskXmlHasPrefixedTag(logon, "UserId") && taskXmlElementCount(logon, "UserId") === 0) return true; - return windowsTaskUserIdMatches(logon, expectedUserId); -} - /** Validate the stable OpenCodex action, principal, settings, and logon trigger. */ function windowsTaskRegistrationBaseHealthy( xml: string, @@ -620,7 +610,6 @@ export function windowsTaskRegistrationHealthy( const scrubbed = taskXmlWithoutCommentsAndCdata(xml); const triggers = taskXmlSection(scrubbed, "Triggers"); return windowsTaskRegistrationBaseHealthy(xml, wscript, launcher) - && windowsTaskLogonScopeMatches(triggers, expectedUserId ?? undefined) // Without these the task can only recover at the next logon, so a disconnected session // leaves the proxy down indefinitely. Treating their absence as unhealthy is what lets // an already-registered task from an older install get repaired instead of staying broken. @@ -653,9 +642,7 @@ export function windowsTaskRegistrationMatchesForStop(xml: string, launcher: str if (!windowsTaskRegistrationBaseHealthy(xml, windowsWscript(), launcher, { allowLossyPaths: false, allowDisabled: true }) || !windowsTaskPrincipalMatches(xml, userIds)) return false; const triggers = taskXmlSection(taskXmlWithoutCommentsAndCdata(xml), "Triggers"); - const legacy = windowsTaskHasNoSessionRecoveryTriggers(triggers); - return windowsTaskLogonScopeMatches(triggers, userIds, legacy) - && (legacy || windowsTaskHasSessionRecoveryTriggers(triggers, userIds)); + return windowsTaskHasSessionRecoveryTriggers(triggers, userIds) || windowsTaskHasNoSessionRecoveryTriggers(triggers); } export interface WindowsSchedulerXmlState { diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index e49c11c0785..e556fb82989 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -36,12 +36,12 @@ one capped PowerShell snapshot that emits UTF-8 JSON and uses ISO UTC for `Creat It reads owner SIDs for command lines carrying this home's launcher or service script as complete tokens first, then other wrapper images, unreadable images, and command lines containing the fixed `opencodex-service` basename prefix. Owner enrichment admits at most 32 candidates within -1.5 s including enumeration and prioritization, with a 1 s operation timeout on each owner or refresh -call. Owner reads and refreshes also stop at the snapshot timeout minus 2 s, measured from -the helper process's start. A complete framed table is emitted before optional owner enrichment, so a timeout during -enrichment retains the original rows with unknown owners. A complete enriched frame supersedes -that baseline. Owner evidence arriving at or after either cutoff is discarded. -Owner verification requires a successful `GetOwnerSid`, +1.5 s after enumeration and prioritization, with a 1 s operation timeout on each owner or refresh +call. No owner read starts later than the snapshot timeout minus 2 s, counted from the +helper process's start, so a cold PowerShell start or slow first CIM query cannot push owner +enrichment past the cap and lose the whole table. Every row is retained and skipped owners +remain unknown. The refresh is skipped if +the owner query spends the budget. Owner verification requires a successful `GetOwnerSid`, valid local/domain or Entra ID SIDs, and a fresh CIM read reporting the original creation time. Matching SIDs prove the current account. Different supported SIDs prove a foreign account. Built-in and virtual service SIDs and failed or skipped lookups leave ownership unverified. @@ -88,21 +88,8 @@ manager still running is `survived` (`unbound-wrapper` when the survivor was nev is `survived` while the proxy is still alive after the service reports stopped. The authorizer variant `guardedStopWindowsServiceChecked` runs its authorizer at entry, before each manager stop and before each terminate and reports a refusal as `WindowsCheckedStopRefusedError` with what had already happened. For Task -Scheduler it reauthorizes after validating the helper proof, before sending `stop-before` on stdin. The -helper and outer deadlines must still be open after authorization. The helper starts its -monotonic clock before sending proof. The parent measures from proof receipt and sends the -earlier deadline as a cutoff on that clock. Time spent delivering approval and refreshing -instances counts toward the cutoff, which the helper checks before each `Stop()`. The outer cap also aborts -the owned helper, including while its registration or instance refresh is pending. -Task-stop verdicts carry separate mutation evidence: a known failure before dispatch leaves -`changed` false even if proof was approved, an attempted stop keeps it true, and a lost answer after dispatch is conservative. -Dispatching approval marks a pending possible mutation until a completed helper verdict proves -otherwise; a timer between dispatch and the first stdout marker must not report `changed: false`. -The helper's `stop-attempted` marker confirms mutation as it arrives. Part A publishes detached -progress at these boundaries, so an outer timer can return pending dispatch and confirmed stop attempts, -bound wrappers and terminations without awaiting unfinished verification. Returned arrays and -records do not change when a late dependency completes. -An authorizer refusal before the outer cap throws with its partial result; after cap expiry it returns the detached cap snapshot with completed mutation evidence. +Scheduler it reauthorizes after validating the helper proof, before sending `stop` on stdin. The +helper and outer deadlines must still be open after authorization. For the Korean Scheduler status, `사용 안 함` (disabled) proves inactivity and `대기` (queued) remains active because that instance can still start. @@ -142,16 +129,14 @@ terminate, the exit watch, the Part B port sampler and the listener identity. in one Task Scheduler COM session. It passes the registered XML and the helper's current account as base64 UTF-8 to preserve Unicode through the console. The live adapter checks the recognized task shape, the exact launcher, and the single run-as principal through `src/service/windows-taskxml.ts`. -The logon scope and every recovery-trigger scope must match the expected account. Only the -recognized legacy shape without recovery triggers may omit the logon scope. The stop proof accepts a disabled task with the same +Trigger user IDs are checked separately. The stop proof accepts a disabled task with the same ownership evidence. Installation health still requires an enabled task. The helper requires a successful same-account SID check for every `EnginePID`, with the process creation time re-read after the owner lookup. After approval it re-reads the registration XML and refreshes every captured instance to verify that its GUID, engine PID and running state still agree. It stops each captured `IRunningTask` by instance GUID. An empty collection counts as idle only if the task is ready or disabled. Failed proof returns `evidence-unreadable` with instructions to -verify the task in Task Scheduler and repair an owned registration or contact its owner or -administrator. Ending a running instance alone does not repair an unverifiable registration. +verify the task in Task Scheduler and stop it from its owning session. The Scheduler exposes current registration XML separately from instance identity. An instance already running under the same account from an earlier definition can still be visible under that @@ -230,9 +215,7 @@ stop instead of sliding forward. own Part A only for a record whose managers are still the registered ones; a receipt without it runs Part A capped at 6 s; without a receipt a registered WinSW keeps its in-process stop and anything else gets the stray sweep capped at 4 s. A cap overrun is `service_state_unknown`, and - the manager commands and terminates are gated off once the cap has passed, including after - asynchronous authorization. A completed late result retains known mutation and termination - records while reporting the cap refusal instead of success. + the manager commands and terminates are gated off once the cap has passed. - `ocx service stop` (`src/service/cli-windows-stop.ts`) refuses on a Part A other than stopped or absent, claims a teardown receipt before the deferred tracked-proxy stop when this home owns the shared teardown (a failed claim sends no child stop), runs Part B, and clears the receipt only @@ -331,5 +314,3 @@ service commands, the guarded order, `bound-stray`, the orphan-discovery cap and evidence snapshot), `tests/windows/windows-guarded-manager.test.ts` (the not-running promotion behind its registration proof) and `tests/windows/windows-stop-ocx-stop.test.ts` (plain `ocx stop` through the real CLI with the platform simulated). -`tests/windows/windows-stop-boundary.test.ts` covers trigger ownership, cap authorization, -mutation evidence and complete process-table retention across interrupted enrichment. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ce0b98ebb76..9c7bad6e1da 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1636,7 +1636,7 @@ "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", - "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-boundary.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", + "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", "windows-process-priority.test.ts": "windows", "windows-scheduler-errors.test.ts": "windows", "windows-scheduler-install-verification.test.ts": "windows", "windows-lifecycle-root-acl.test.ts": "windows", diff --git a/tests/service/service.test.ts b/tests/service/service.test.ts index f21c8488898..9ed6bf82335 100644 --- a/tests/service/service.test.ts +++ b/tests/service/service.test.ts @@ -975,10 +975,10 @@ describe("Windows service task", () => { // Windows drops elements equal to their schema default when it exports a task: // Trigger/Settings Enabled default to true and RunLevel defaults to LeastPrivilege. const canonical = xml - .replace(LOGON_TRIGGER_BLOCK, `${TEST_WINDOWS_TASK_SID}`) + .replace(LOGON_TRIGGER_BLOCK, "") .replace(" LeastPrivilege\n", "") .replace(" true\n ", " "); - expect(canonical).toContain(`${TEST_WINDOWS_TASK_SID}`); + expect(canonical).toContain(""); expect(canonical).not.toContain("RunLevel"); expect(windowsTaskRegistrationHealthy(canonical, wscript, launcher)).toBe(true); diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index dd53dd279fd..26060d13062 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -278,28 +278,14 @@ test.skipIf(process.platform !== "win32" && !portablePowerShell)("the PowerShell $script:scenario = $args[0] $script:sid = 'S-1-5-21-100-200-300-1001' $script:taskReads = 0 -$script:elapsed = 0 -function Start-FixtureClock { - $clock = [pscustomobject]@{ Started = $script:elapsed } - $clock | Add-Member ScriptProperty ElapsedMilliseconds { $script:elapsed - $this.Started } - $clock -} -function Read-FixtureApproval { - if ($script:scenario -eq 'late-approval') { $script:elapsed = 2000 } - [Console]::ReadLine() -} $script:stopped = [Collections.Generic.List[int]]::new() function New-Instance($enginePid) { $obj = [pscustomobject]@{ EnginePID = $enginePid; State = 4; InstanceGuid = [Guid]::NewGuid(); Reads = 0 } $obj | Add-Member ScriptMethod Refresh { $this.Reads++ if ($script:scenario -eq 'engine-changed' -and $this.Reads -eq 2) { $this.EnginePID++ } - if ($script:scenario -eq 'deadline-before-first' -and $this.Reads -eq 2) { $script:elapsed = 2000 } - } - $obj | Add-Member ScriptMethod Stop { - $script:stopped.Add($this.EnginePID) - if ($script:scenario -eq 'deadline-between-stops') { $script:elapsed = 2000 } } + $obj | Add-Member ScriptMethod Stop { $script:stopped.Add($this.EnginePID) } return $obj } $instances = [pscustomobject]@{ Rows = @((New-Instance 42), (New-Instance 43)) } @@ -343,8 +329,6 @@ function Invoke-CimMethod { } `; const helper = WINDOWS_TASK_INSTANCE_STOP_SCRIPT - .replace("[Diagnostics.Stopwatch]::StartNew()", "Start-FixtureClock") - .replace("[Console]::ReadLine()", "Read-FixtureApproval") .replace(/^\s*Import-Module .*'CimCmdlets\.psd1'.*$/m, "") .replaceAll("CimCmdlets\\", "") .replace("Microsoft.PowerShell.Utility\\New-Object -ComObject Schedule.Service", "New-Object -ComObject FixtureScheduler") @@ -352,7 +336,7 @@ function Invoke-CimMethod { "([pscustomobject]@{ User = @{ Value = $script:sid }; Name = 'HOST\\test' })"); expect(helper).toContain("$service = New-Object -ComObject FixtureScheduler"); expect(helper).not.toContain("Schedule.Service"); - // All launches share one 60 s window (each capped at the spawn budget), so a hang fails here + // All eight launches share one 60 s window (each capped at the spawn budget), so a hang fails here // with the active scenario named, inside the 120 s Linux batch deadline. const deadline = Date.now() + 60_000; for (const [scenario, status, stopped] of [ @@ -364,9 +348,6 @@ function Invoke-CimMethod { ["rejected", "unverified-registration", ""], ["hidden", "unverified-registration", ""], ["idle", "not-running", ""], - ["late-approval", "failed", ""], - ["deadline-before-first", "failed", ""], - ["deadline-between-stops", "failed", "42"], ]) { // Production runs the helper alone, which silences progress before its first module use. The fixture // runs first here and its Add-Member/[pscustomobject] calls autoload Microsoft.PowerShell.Utility, which @@ -377,7 +358,7 @@ function Invoke-CimMethod { stdio: ["pipe", "pipe", "pipe"], windowsHide: true, timeout: Math.max(1_000, Math.min(SPAWN_BUDGET_MS, deadline - Date.now())), }); - child.stdin.write(scenario === "rejected" ? "\n" : "stop-before 2000\n"); + child.stdin.write(scenario === "rejected" ? "\n" : "stop\n"); child.stdin.end(); const [stdout, stderr, code] = await Promise.all([ new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited, diff --git a/tests/windows/windows-process-evidence.test.ts b/tests/windows/windows-process-evidence.test.ts index ad3e46f8826..4091cb8f4bf 100644 --- a/tests/windows/windows-process-evidence.test.ts +++ b/tests/windows/windows-process-evidence.test.ts @@ -240,17 +240,6 @@ const liveX64 = process.platform !== "win32" || process.arch !== "x64"; const portablePowerShell = Bun.which("pwsh"); -const ownerBudgetCases = { - available: [32, 32], - expired: [0, 0], - "expires-during-enumeration": [0, 0], - "expires-during-owner": [1, 0], - "expires-during-refresh": [1, 1], - "cap-reached": [0, 0], - "cap-during-owner": [1, 0], - "cap-during-refresh": [1, 1], -} as const; - // The budgets run in one test that shares one 60 s window: a slow first PowerShell start may use // most of it, but a hang still fails inside the 120 s Linux batch deadline, naming the active budget. // "cap-reached" is the hosted-runner regression: the loop's own 1.5 s budget is fresh, but the @@ -259,32 +248,28 @@ const ownerBudgetCases = { // refresh read must not start either. test.skipIf(process.platform !== "win32" && !portablePowerShell)("owner enrichment prioritizes this home and retains every row", async () => { const deadline = Date.now() + 60_000; - for (const budget of Object.keys(ownerBudgetCases) as (keyof typeof ownerBudgetCases)[]) { + for (const budget of ["available", "expired", "expires-during-owner", "cap-reached", "cap-during-owner"] as const) { try { await ownerEnrichmentCase(budget, deadline); } catch (error) { throw new Error("budget=" + budget + ": " + (error instanceof Error ? error.message : String(error)), { cause: error }); } } }, 65_000); -async function ownerEnrichmentCase(budget: keyof typeof ownerBudgetCases, deadline: number): Promise { +async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-during-owner" | "cap-reached" | "cap-during-owner", deadline: number): Promise { const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!; const launcher = Buffer.from(windowsLauncherVbsPath(), "utf8").toString("base64"); // A cap equal to the reserve puts the owner cutoff at the helper's own start. const script = windowsProcessSnapshotScript(budget === "cap-reached" ? SNAPSHOT_OWNER_RESERVE_MS : 60_000).replace( "[Security.Principal.WindowsIdentity]::GetCurrent().User.Value", "'S-1-5-21-100-200-300-1001'", - ).replace("[Diagnostics.Stopwatch]::StartNew()", "(New-FixtureClock)"); + ).replace("[Diagnostics.Stopwatch]::StartNew()", "[pscustomobject]@{ ElapsedMilliseconds = " + (budget === "expired" ? 1500 : 0) + " }"); const prelude = [ "$script:ownerReads = 0; $script:refreshReads = 0;", - "function New-FixtureClock { $script:elapsed = " + (budget === "expired" ? 1500 : 0) + "; $clock = [pscustomobject]@{};", - " $clock | Add-Member ScriptProperty ElapsedMilliseconds { $script:elapsed }; return $clock };", "function Get-CimInstance { param($ClassName, $InputObject, $ErrorAction, $OperationTimeoutSec)", - " if ($InputObject) { $script:refreshReads++; " + (budget === "expires-during-refresh" ? "$script:elapsed = 1500; " : "") - + (budget === "cap-during-refresh" ? "$ownerBudget.Until = [DateTime]::UtcNow.AddMinutes(-1); " : "") + "return $InputObject };", - budget === "expires-during-enumeration" ? "$script:elapsed = 1500;" : "", + " if ($InputObject) { $script:refreshReads++; return $InputObject };", " 1..40 | ForEach-Object { [pscustomobject]@{ ProcessId = $_; ParentProcessId = 900; Name = 'cmd.exe';", " CommandLine = if ($_ -eq 40) { 'wscript.exe \"' + [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + launcher + "')) + '\"' } else { 'cmd.exe' };", " CreationDate = [datetime]'2026-11-12T01:02:03Z' } } };", "function Invoke-CimMethod { param($InputObject, $MethodName, $ErrorAction, $OperationTimeoutSec)", - " $script:ownerReads++; " + (budget === "expires-during-owner" ? "$script:elapsed = 1500; " : "") + " $script:ownerReads++; " + (budget === "expires-during-owner" ? "$ownerBudget.Clock.ElapsedMilliseconds = 1500; " : "") + (budget === "cap-during-owner" ? "$ownerBudget.Until = [DateTime]::UtcNow.AddMinutes(-1); " : "") + "@{ Sid = $currentSid; ReturnValue = 0 } };", "$rows = & { " + script + " };", @@ -301,14 +286,14 @@ async function ownerEnrichmentCase(budget: keyof typeof ownerBudgetCases, deadli expect(errors).toBe(""); expect(exitCode).toBe(0); const result = JSON.parse(output); - const rows = parseWindowsProcessSnapshot(Array.isArray(result.Snapshot) ? result.Snapshot.join("\n") : result.Snapshot)!; + const rows = parseWindowsProcessSnapshot(result.Snapshot)!; expect(rows).toHaveLength(40); expect(rows.map(row => row.pid)).toEqual(Array.from({ length: 40 }, (_, index) => index + 1)); - const [ownerReads, refreshReads] = ownerBudgetCases[budget]; - expect(result.OwnerReads).toBe(ownerReads); - expect(result.RefreshReads).toBe(refreshReads); + expect(result.OwnerReads).toBe(budget === "available" ? 32 : budget === "expires-during-owner" || budget === "cap-during-owner" ? 1 : 0); + const refreshed = budget === "available" ? 32 : 0; + expect(result.RefreshReads).toBe(refreshed); expect(rows[39]!.foreignOwner).toBe(budget === "available" ? false : null); - const ordinaryRefreshed = budget === "available" ? 31 : 0; + const ordinaryRefreshed = Math.max(0, refreshed - 1); expect(rows.slice(0, ordinaryRefreshed).every(row => row.foreignOwner === false)).toBe(true); expect(rows.slice(ordinaryRefreshed, 39).every(row => row.foreignOwner === null)).toBe(true); } diff --git a/tests/windows/windows-stop-boundary.test.ts b/tests/windows/windows-stop-boundary.test.ts deleted file mode 100644 index 2aa9e7409f2..00000000000 --- a/tests/windows/windows-stop-boundary.test.ts +++ /dev/null @@ -1,285 +0,0 @@ -import { afterEach, expect, spyOn, test } from "bun:test"; -import { stopWindowsServiceChecked, WindowsCheckedStopRefusedError, type WindowsCheckedStopDeps } from "../../src/service/windows-checked-stop"; -import { windowsCheckedStopLiveDeps } from "../../src/service/windows-checked-stop-live"; -import { parseWindowsProcessSnapshot, windowsProcessSnapshot } from "../../src/service/windows-process-evidence"; -import { setWindowsProcessNativeForTests } from "../../src/service/windows-process-native"; -import { runWindowsServiceStopPartA, setWindowsServiceStopHooksForTests } from "../../src/service/windows-service-stop"; -import { windowsLauncherVbsPath } from "../../src/service/state"; -import { verifyWindowsTaskStopProof } from "../../src/service/windows-task-instance-stop"; -import { buildWindowsTaskXml, windowsTaskRegistrationHealthy } from "../../src/service/windows-taskxml"; -import { PATHS, SCHEDULE_PID, supervisedTree } from "../helpers/windows-checked-stop-fixtures"; -import { partAResult } from "../helpers/windows-stop-caller-fixtures"; - -afterEach(() => { - setWindowsServiceStopHooksForTests(null); - setWindowsProcessNativeForTests(undefined); -}); - -const SID = "S-1-5-21-100-200-300-1001"; -const FOREIGN = "S-1-5-21-100-200-300-1002"; -const launcher = windowsLauncherVbsPath(); -const ownedXml = buildWindowsTaskXml(undefined, launcher, undefined, SID) - .replace('', `${SID}`); -const proof = (xml: string) => Buffer.from(JSON.stringify({ xml, sid: SID })).toString("base64"); -const legacy = (xml: string) => xml.replace(/[\s\S]*?<\/SessionStateChangeTrigger>/g, ""); - -function machine(overrides: Partial = {}) { - const terminated: number[] = []; - const dead = new Set(); - const deps: WindowsCheckedStopDeps = { - canonicalPaths: PATHS, childPid: 42, selfPid: 1, - probeScheduler: () => ({ status: "present" }), probeWinsw: () => "nonexistent", - enumerate: () => supervisedTree(), scheduleServicePid: () => SCHEDULE_PID, - endTask: () => "ended", taskState: () => "not-running", winswStop: () => "sent", - winswState: () => "stopped", proxyAlive: () => false, - openWatch: pid => ({ status: "open", exited: () => dead.has(pid), close() {} }), - terminate: pid => { terminated.push(pid); dead.add(pid); return { status: "terminated", exited: true }; }, - ...overrides, - }; - return { deps, terminated }; -} - -for (const oldShape of [false, true]) { - test(`Scheduler stop refuses a foreign logon scope in the ${oldShape ? "legacy" : "recovery"} shape`, () => { - const xml = (oldShape ? legacy(ownedXml) : ownedXml).replace(/([\s\S]*?)[^<]+/, `$1${FOREIGN}`); - expect(verifyWindowsTaskStopProof(proof(xml), launcher)).toBe(false); - expect(windowsTaskRegistrationHealthy(xml, undefined, launcher, SID)).toBe(false); - }); -} - -for (const scope of [FOREIGN, "", "prefixed", "self-closing"]) { - test(`Scheduler stop and installation health refuse an additional ${scope || "unscoped"} recovery trigger`, () => { - const extra = scope === "self-closing" ? "" - : scope === "prefixed" ? `${FOREIGN}` - : `ConsoleConnect${scope ? `${scope}` : ""}`; - const xml = ownedXml.replace("", extra + ""); - expect(verifyWindowsTaskStopProof(proof(xml), launcher)).toBe(false); - expect(windowsTaskRegistrationHealthy(xml, undefined, launcher, SID)).toBe(false); - }); -} - -test("owned trigger scopes and the recognized unscoped legacy logon remain valid", () => { - expect(verifyWindowsTaskStopProof(proof(ownedXml), launcher)).toBe(true); - expect(windowsTaskRegistrationHealthy(ownedXml, undefined, launcher, SID)).toBe(true); - const unscopedLegacy = legacy(ownedXml).replace(/([\s\S]*?)[^<]+<\/UserId>/, "$1"); - expect(verifyWindowsTaskStopProof(proof(unscopedLegacy), launcher)).toBe(true); - const unscopedCurrent = ownedXml.replace(/([\s\S]*?)[^<]+<\/UserId>/, "$1"); - expect(verifyWindowsTaskStopProof(proof(unscopedCurrent), launcher)).toBe(false); -}); - -test("an asynchronous authorizer cannot dispatch a wrapper terminate after the outer cap", async () => { - let elapsed = 0, approvals = 0; - const now = spyOn(performance, "now").mockImplementation(() => elapsed); - const fake = machine(); - setWindowsServiceStopHooksForTests({ liveDeps: () => fake.deps }); - try { - const result = await runWindowsServiceStopPartA({ capMs: 50, authorize: async () => { - await Promise.resolve(); - if (++approvals === 3) elapsed = 50; - } }); - expect(approvals).toBe(3); - expect(fake.terminated).toEqual([]); - expect(result).toMatchObject({ outcome: "unknown", changed: true, terminated: [] }); - expect(result.detail).toBe("the checked stop did not finish within its cap"); - expect(result.bound.map(row => row.pid)).toEqual([30, 20]); - } finally { now.mockRestore(); } -}); - -test("an explicit authorizer refusal inside the cap still throws with the completed stop evidence", async () => { - let approvals = 0; - const fake = machine(); - const refusal = new Error("stop permission withdrawn"); - setWindowsServiceStopHooksForTests({ liveDeps: () => fake.deps }); - const failure = await runWindowsServiceStopPartA({ capMs: 1_000, authorize: () => { - if (++approvals === 3) throw refusal; - } }).catch(error => error); - expect(failure).toBeInstanceOf(WindowsCheckedStopRefusedError); - expect(failure.cause).toBe(refusal); - expect(failure.partial).toMatchObject({ outcome: "unknown", changed: true, terminated: [] }); - expect(fake.terminated).toEqual([]); -}); - -test("an explicit authorizer refusal after the cap returns the detached cap snapshot", async () => { - let elapsed = 0, approvals = 0; - const now = spyOn(performance, "now").mockImplementation(() => elapsed); - const fake = machine(); - setWindowsServiceStopHooksForTests({ liveDeps: () => fake.deps }); - try { - const result = await runWindowsServiceStopPartA({ capMs: 50, authorize: async () => { - await Promise.resolve(); - if (++approvals === 3) { elapsed = 50; throw new Error("stop permission withdrawn"); } - } }); - expect(result).toMatchObject({ outcome: "unknown", changed: true, terminated: [] }); - expect(result.detail).toBe("the checked stop did not finish within its cap"); - expect(result.bound.map(row => row.pid)).toEqual([30, 20]); - expect(fake.terminated).toEqual([]); - } finally { now.mockRestore(); } -}); - -test("an authorizer that completes inside the cap preserves ordinary wrapper termination", async () => { - const fake = machine(); - setWindowsServiceStopHooksForTests({ liveDeps: () => fake.deps }); - const result = await runWindowsServiceStopPartA({ capMs: 500, authorize: async () => { await Promise.resolve(); } }); - expect(result.outcome).toBe("stopped"); - expect(fake.terminated).toEqual([30, 20]); -}); - -test("the live terminate checks the cap immediately before entering the native primitive", async () => { - let terminated = 0; - setWindowsProcessNativeForTests({ creationTime: () => 5_000, scheduleServicePid: () => null, - openWatch: () => ({ status: "unavailable" }), - terminate: () => { terminated++; return { status: "terminated" }; }, - }); - const deps = windowsCheckedStopLiveDeps({ gate: () => false }); - expect(await deps.terminate(20, 5_000, 1_000)).toEqual({ status: "unavailable" }); - expect(terminated).toBe(0); -}); - -test("a late Part A result preserves known mutation and termination evidence while refusing success", async () => { - let elapsed = 0; - const now = spyOn(performance, "now").mockImplementation(() => elapsed); - const known = { ...partAResult("stopped"), changed: true, terminated: [30, 20] }; - setWindowsServiceStopHooksForTests({ partA: async () => { elapsed = 50; return known; } }); - try { - const result = await runWindowsServiceStopPartA({ capMs: 50 }); - expect(result).toMatchObject({ outcome: "unknown", reason: "evidence-unreadable", changed: true, terminated: [30, 20] }); - expect(result.detail).toBe("the checked stop did not finish within its cap"); - } finally { now.mockRestore(); } -}); - -test("the outer timer preserves completed stops while final verification is pending", async () => { - let release!: (state: "not-running") => void; - const fake = machine({ taskState: () => new Promise(resolve => { release = resolve; }) }); - setWindowsServiceStopHooksForTests({ liveDeps: () => fake.deps }); - const result = await runWindowsServiceStopPartA({ capMs: 100 }); - release("not-running"); - await Bun.sleep(0); - expect(result).toMatchObject({ outcome: "unknown", changed: true, terminated: [30, 20], registration: { scheduler: "present" } }); - expect(result.bound.map(row => row.pid)).toEqual([30, 20]); -}); - -test("a returned cap snapshot cannot acquire termination evidence from a late dependency", async () => { - let release!: () => void; - const fake = machine({ terminate: pid => pid === 30 ? { status: "terminated", exited: true } - : new Promise(resolve => { release = () => resolve({ status: "terminated", exited: true }); }) }); - setWindowsServiceStopHooksForTests({ liveDeps: () => fake.deps }); - const result = await runWindowsServiceStopPartA({ capMs: 100 }); - release(); - await Bun.sleep(0); - expect(result).toMatchObject({ outcome: "unknown", changed: true, terminated: [30] }); - expect(result.terminated).toEqual([30]); - expect(result.outcome).toBe("unknown"); -}); - -for (const crossesOuterCap of [false, true]) { - test(`Scheduler post-proof refresh ${crossesOuterCap ? "cannot cross" : "can finish inside"} the outer budget`, async () => { - let elapsed = 0, commandBudget = 0, stopBudget = 0, stops = 0; - const now = spyOn(performance, "now").mockImplementation(() => elapsed); - setWindowsServiceStopHooksForTests({ liveDeps: options => { - const live = windowsCheckedStopLiveDeps({ ...options, run: async (_program, _args, timeoutMs, approve, control) => { - commandBudget = timeoutMs; - if (!await approve?.(proof(ownedXml))) return { status: 0, stdout: "failed", stderr: "", timedOut: false }; - stopBudget = Math.min(timeoutMs, control?.remainingMs?.() ?? Infinity); - // The real helper checks its received budget after refreshing captured instances. - const refreshMs = crossesOuterCap ? 25 : 5; - elapsed += refreshMs; - if (refreshMs >= stopBudget) return { status: 0, stdout: "failed", stderr: "", timedOut: false }; - stops++; - control?.onMutation?.(); - return { status: 0, stdout: "stop-attempted\nended", stderr: "", timedOut: false }; - } }); - return machine({ enumerate: () => [], endTask: live.endTask }).deps; - } }); - let approvals = 0; - try { - const result = await runWindowsServiceStopPartA({ capMs: 50, authorize: () => { - if (++approvals === 3) elapsed = 30; - } }); - expect(commandBudget).toBe(50); - expect(stopBudget).toBe(20); - expect(stops).toBe(crossesOuterCap ? 0 : 1); - expect(result.changed).toBe(!crossesOuterCap); - expect(result.outcome).toBe(crossesOuterCap ? "unknown" : "stopped"); - } finally { now.mockRestore(); } - }); -} - -test("the outer cap aborts a pending helper and retains dispatch or streamed mutation evidence", async () => { - for (const stage of ["unapproved", "dispatched", "attempted"] as const) { - let aborted = false, approved = false; - let reap: (() => void) | undefined; - setWindowsServiceStopHooksForTests({ liveDeps: options => { - const live = windowsCheckedStopLiveDeps({ ...options, run: async (_program, _args, _timeout, approve, control) => { - if (stage !== "unapproved") { - approved = await approve?.(proof(ownedXml)) === true; - control?.onDispatch?.(); - } - if (stage === "attempted") control?.onMutation?.(); - return new Promise(resolve => { - reap = () => resolve({ status: null, stdout: "", stderr: "", timedOut: true }); - // Keep the helper pending through the outer return: no final result or marker may - // fill in evidence on behalf of the dispatched-but-unanswered case. - const abort = () => { aborted = true; }; - if (control?.signal?.aborted) abort(); - else control?.signal?.addEventListener("abort", abort, { once: true }); - }); - } }); - return machine({ enumerate: () => [], endTask: live.endTask }).deps; - } }); - const result = await runWindowsServiceStopPartA({ capMs: 100 }); - reap?.(); - await Bun.sleep(0); - expect(approved).toBe(stage !== "unapproved"); - expect(aborted).toBe(true); - expect(result).toMatchObject({ outcome: "unknown", changed: stage !== "unapproved", terminated: [] }); - } -}); - -for (const outcome of ["failed-before-dispatch", "unverified", "budget-before-stop", "partial-stop", "denied-after-stop", "lost-after-approval", "lost-successful-result", - "approved-not-dispatched-timeout", "approved-not-dispatched-failed", "approved-not-dispatched-empty"] as const) { - test(`Scheduler mutation evidence survives ${outcome}`, async () => { - const live = windowsCheckedStopLiveDeps({ run: async (_program, _args, _timeout, authorizeProof, control) => { - if (outcome === "failed-before-dispatch") return { status: null, stdout: "", stderr: "PowerShell not found", timedOut: false }; - if (outcome === "unverified") return { status: 0, stdout: "unverified-registration", stderr: "", timedOut: false }; - expect(await authorizeProof?.(proof(ownedXml))).toBe(true); - if (outcome.startsWith("approved-not-dispatched-")) return { - status: outcome === "approved-not-dispatched-empty" ? 0 : null, - stdout: "", stderr: "", timedOut: outcome === "approved-not-dispatched-timeout", - }; - control?.onDispatch?.(); - if (outcome === "budget-before-stop" || outcome === "lost-successful-result") return { - status: 0, stdout: outcome === "budget-before-stop" ? "failed" : "", stderr: "", timedOut: false, - }; - return { status: outcome === "lost-after-approval" ? null : 0, - stdout: outcome === "lost-after-approval" ? "" : `stop-attempted\n${outcome === "denied-after-stop" ? "denied" : "failed"}`, - stderr: "", timedOut: outcome === "lost-after-approval" }; - } }); - const fake = machine({ enumerate: () => [], endTask: live.endTask }); - const result = await stopWindowsServiceChecked(fake.deps); - expect(result.outcome).toBe(outcome === "denied-after-stop" ? "denied" : "unknown"); - expect(result.changed).toBe(!["failed-before-dispatch", "unverified", "budget-before-stop"].includes(outcome) - && !outcome.startsWith("approved-not-dispatched-")); - expect(fake.terminated).toEqual([]); - }); -} - -test("a complete process table survives interrupted owner enrichment with ownership left unknown", async () => { - const rows = [{ ProcessId: 20, ParentProcessId: 4, Name: "cmd.exe", CommandLine: "cmd.exe", CreationDate: "2026-11-12T01:02:03Z", CurrentUserSid: SID }]; - const baseline = "OCX_PROCESS_SNAPSHOT " + JSON.stringify(rows) + "\n"; - setWindowsProcessNativeForTests(null); - const result = await windowsProcessSnapshot({ timeoutMs: 5_000, run: async command => { - expect(command).toMatchObject({ allowPartialOutput: true }); - return baseline + "OCX_PROCESS_SNAPSHOT [{\"ProcessId\":"; - } }); - expect(result).toEqual([{ pid: 20, parentPid: 4, name: "cmd.exe", commandLine: "cmd.exe", - startTime: Date.parse(rows[0]!.CreationDate), foreignOwner: null }]); - expect(parseWindowsProcessSnapshot("OCX_PROCESS_SNAPSHOT [{")).toBeNull(); -}); - -test("completed owner enrichment supersedes the baseline only with a complete snapshot", () => { - const row = { ProcessId: 20, ParentProcessId: 4, Name: "cmd.exe", CommandLine: "cmd.exe", - CreationDate: "2026-11-12T01:02:03Z", CurrentUserSid: SID }; - const final = { ...row, Owner: { Sid: FOREIGN, ReturnValue: 0, CreationDate: row.CreationDate } }; - const output = `OCX_PROCESS_SNAPSHOT ${JSON.stringify([row])}\nOCX_PROCESS_SNAPSHOT ${JSON.stringify([final])}\n`; - expect(parseWindowsProcessSnapshot(output)?.[0]?.foreignOwner).toBe(true); -});