Skip to content

Commit e5f9054

Browse files
committed
fix(service): verify a scheduler path the console code page cannot carry
A Windows profile directory outside the console code page made verifyWindowsSchedulerInstall reject a valid task and roll back a successful elevated create: windowsTaskRegistrationHealthy compares Command and Arguments against the local paths, and the value schtasks reported no longer equalled them. The reported cause -- that runFile() applies a code-page conversion the raw bytes would avoid -- is not where it happens. runFile already reads with encoding: "buffer", and under Bun on Windows execFileSync and Bun.spawnSync return byte-identical output; I measured both against a UTF-16LE fixture. The conversion is schtasks' own: with stdout redirected, `/query /tn X /xml` emits console-code-page bytes, not the UTF-16LE the decoder documents. On this machine the document starts `3c 3f 78 6d 6c` -- `<?xml`, no BOM. So the characters are already gone before any decoder runs, and switching spawn APIs cannot recover them. Compare those two values as paths instead. The expected path is matched literally except across a run the code page could not carry, where anything is accepted -- "?" per character, U+FFFD, or nothing -- but never a path separator, so every directory the path names is still verified and a task pointing somewhere else still fails. An all-ASCII path is unaffected: there is nothing unrepresentable in it, so the comparison stays exact. Fixes #3064
1 parent 7ee96b9 commit e5f9054

2 files changed

Lines changed: 100 additions & 3 deletions

File tree

‎src/service.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1935,6 +1935,46 @@ function taskXmlDecodedValueEquals(xml: string, tag: string, expected: string):
19351935
return taskXmlDecodeEntities(value).trim().toLowerCase() === expected.trim().toLowerCase();
19361936
}
19371937

1938+
/**
1939+
* Compare a path Task Scheduler reported against the one we registered.
1940+
*
1941+
* `schtasks /query /tn X /xml` writes through the console code page when stdout
1942+
* is a pipe, not UTF-16, so a profile directory outside that code page is
1943+
* already mangled in the bytes we receive -- there is nothing left on our side
1944+
* to decode. A valid task therefore failed the Command/Arguments comparison and
1945+
* a successful elevated create was rolled back (#3064).
1946+
*
1947+
* When, and only when, the path we expect contains characters that transport
1948+
* could not carry, compare what it *could* carry: every run of non-ASCII on both
1949+
* sides collapses to one placeholder. A task pointing somewhere genuinely
1950+
* different still differs in its ASCII structure and still fails.
1951+
*/
1952+
export function taskXmlPathEquals(reported: string, expected: string): boolean {
1953+
const a = reported.trim().toLowerCase();
1954+
const b = expected.trim().toLowerCase();
1955+
if (a === b) return true;
1956+
if (!/[^\x00-\x7F]/.test(b)) return false;
1957+
// Match the expected path literally except where the code page could not carry
1958+
// it. What came back there depends on the conversion -- "?" per character,
1959+
// U+FFFD, or nothing at all -- so accept any run, but never one containing a
1960+
// path separator: every directory the path names is still verified, and a task
1961+
// pointing at a different folder or file still fails.
1962+
const pattern = b
1963+
.split(/([^\x00-\x7F]+)/)
1964+
.map((part, index) =>
1965+
index % 2 === 1 ? "[^\\\\/]*" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
1966+
.join("");
1967+
return new RegExp(`^${pattern}$`).test(a);
1968+
}
1969+
1970+
function taskXmlDecodedPathEquals(xml: string, tag: string, expected: string): boolean {
1971+
if (taskXmlHasPrefixedTag(xml, tag)) return false;
1972+
if (taskXmlElementCount(xml, tag) !== 1) return false;
1973+
const value = new RegExp(`<${tag}(?:\\s[^>]*?)?>([^<]*)<\\/${tag}>`, "i").exec(xml)?.[1];
1974+
if (value === undefined) return false;
1975+
return taskXmlPathEquals(taskXmlDecodeEntities(value), expected);
1976+
}
1977+
19381978
function taskXmlOptionalValueEquals(xml: string, tag: string, expected: string): boolean {
19391979
// Check the prefixed form first: treating `<t:Enabled>false</t:Enabled>` as an
19401980
// omission would turn an explicitly disabled task into a healthy one.
@@ -2030,8 +2070,10 @@ function windowsTaskRegistrationBaseHealthy(
20302070
// quotes we wrote as `&quot;` back to literal `"` on export, so an escaped
20312071
// needle never matched and a healthy task read as permanently stale (#608).
20322072
// Case-insensitive: elevated `schtasks /create` may rewrite System32 casing.
2033-
&& taskXmlDecodedValueEquals(action, "Command", wscript)
2034-
&& taskXmlDecodedValueEquals(action, "Arguments", `/b /nologo "${launcher}"`);
2073+
// Paths, not plain values: both live under the user profile, which schtasks
2074+
// cannot round-trip through the console code page when it is not ASCII (#3064).
2075+
&& taskXmlDecodedPathEquals(action, "Command", wscript)
2076+
&& taskXmlDecodedPathEquals(action, "Arguments", `/b /nologo "${launcher}"`);
20352077
}
20362078

20372079
/** Validate the security/lifecycle-critical fields of the registered scheduler task. */

‎tests/service.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { pathToFileURL } from "node:url";
77
import * as serviceModule from "../src/service";
88
import { saveConfig } from "../src/config";
99
import { windowsEnvIndirectBatchValue } from "../src/lib/win-paths";
10-
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, confirmServiceServing, launchdListenPort, systemdListenPort, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml, deriveWindowsServiceDiagnostic, deriveWindowsServiceDiagnosticForCurrentUser, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, normalizeServiceSubcommand, parseServiceArgs, parseServiceInstallState, planServiceCommand, prepareServiceInstall, probeServiceInstallation, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, resolveServiceListenPort, runLaunchctl, selectServiceSubcommand, serviceLogPath, serviceStartableFromTray, serviceStatusReport, serviceRetryCommand, serviceStatusSummary, stableLauncherEntry, systemdNeedsDaemonReload, systemdServiceInstallCleanupOps, uninstallSystemd, windowsListenPort, winswListenPort, startLaunchd, windowsTaskRegistrationHealthy } from "../src/service";
10+
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml, confirmServiceServing, deriveWindowsServiceDiagnostic, deriveWindowsServiceDiagnosticForCurrentUser, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, launchdListenPort, normalizeServiceSubcommand, parseServiceArgs, parseServiceInstallState, planServiceCommand, prepareServiceInstall, probeServiceInstallation, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, resolveServiceListenPort, runLaunchctl, selectServiceSubcommand, serviceLogPath, serviceRetryCommand, serviceStartableFromTray, serviceStatusReport, serviceStatusSummary, stableLauncherEntry, startLaunchd, systemdListenPort, systemdNeedsDaemonReload, systemdServiceInstallCleanupOps, taskXmlPathEquals, uninstallSystemd, windowsListenPort, windowsTaskRegistrationHealthy, winswListenPort } from "../src/service";
1111
import type { ServiceDiagnostic } from "../src/service";
1212
import { definitionCarriesCredential, resolvedProxyEnv, writeServiceDefinitionFile } from "../src/service";
1313
import { buildWinswXml } from "../src/lib/winsw";
@@ -582,6 +582,61 @@ describe("Windows service task", () => {
582582
]) expect(windowsTaskRegistrationHealthy(mutated, wscript, launcher)).toBe(false);
583583
});
584584

585+
586+
// --- #3064: a non-ASCII profile path survives the schtasks code page --------
587+
test("accepts a registration whose path the schtasks code page could not carry", () => {
588+
const wscript = "C:\\Windows\\System32\\wscript.exe";
589+
const launcher = "C:\\Users\\Người\\.opencodex\\service-launcher.vbs";
590+
const xml = buildWindowsTaskXml("ignored.cmd", launcher).replace(/<Command>.*?<\/Command>/, `<Command>${wscript}</Command>`);
591+
expect(windowsTaskRegistrationHealthy(xml, wscript, launcher)).toBe(true);
592+
593+
// What `schtasks /query /tn X /xml` actually hands back when stdout is a pipe:
594+
// its output goes through the console code page, so characters outside it are
595+
// already replaced before we read a single byte.
596+
for (const mangled of [
597+
xml.replace("Người", "Ng??i"),
598+
xml.replace("Người", "Ngi"),
599+
xml.replace("Người", "Ng\uFFFDi"),
600+
]) expect(windowsTaskRegistrationHealthy(mangled, wscript, launcher)).toBe(true);
601+
});
602+
603+
test("still rejects a foreign path even when the expected one is non-ASCII", () => {
604+
const wscript = "C:\\Windows\\System32\\wscript.exe";
605+
const launcher = "C:\\Users\\Người\\.opencodex\\service-launcher.vbs";
606+
const xml = buildWindowsTaskXml("ignored.cmd", launcher).replace(/<Command>.*?<\/Command>/, `<Command>${wscript}</Command>`);
607+
for (const mutated of [
608+
xml.replace(launcher, "C:\\Temp\\foreign.vbs"),
609+
xml.replace(launcher, "C:\\Users\\Người\\.opencodex\\other-launcher.vbs"),
610+
xml.replace(launcher, "C:\\Users\\Người\\.evil\\service-launcher.vbs"),
611+
xml.replace(wscript, "C:\\Windows\\System32\\cmd.exe"),
612+
]) expect(windowsTaskRegistrationHealthy(mutated, wscript, launcher)).toBe(false);
613+
});
614+
615+
test("an ASCII path is compared exactly, with no relaxation", () => {
616+
const wscript = "C:\\Windows\\System32\\wscript.exe";
617+
const launcher = "C:\\Users\\Test\\.opencodex\\service-launcher.vbs";
618+
const xml = buildWindowsTaskXml("ignored.cmd", launcher).replace(/<Command>.*?<\/Command>/, `<Command>${wscript}</Command>`);
619+
// A single character off must still fail: nothing about an ASCII path is
620+
// unrepresentable, so there is nothing to forgive.
621+
expect(windowsTaskRegistrationHealthy(xml.replace("\\Test\\", "\\Tost\\"), wscript, launcher)).toBe(false);
622+
expect(windowsTaskRegistrationHealthy(xml.replace("service-launcher", "service-launcherr"), wscript, launcher)).toBe(false);
623+
});
624+
625+
test("the path comparison forgives only unrepresentable characters", () => {
626+
expect(taskXmlPathEquals("C:\\Users\\Người\\x.vbs", "C:\\Users\\Người\\x.vbs")).toBe(true);
627+
expect(taskXmlPathEquals("C:\\Users\\Ng??i\\x.vbs", "C:\\Users\\Người\\x.vbs")).toBe(true);
628+
// Case-insensitive, matching the exact comparison it replaces.
629+
expect(taskXmlPathEquals("c:\\users\\ng??i\\x.vbs", "C:\\Users\\Người\\x.vbs")).toBe(true);
630+
// ASCII differences are never forgiven, on either side of the mangled run.
631+
expect(taskXmlPathEquals("C:\\Users\\Ng??i\\y.vbs", "C:\\Users\\Người\\x.vbs")).toBe(false);
632+
expect(taskXmlPathEquals("D:\\Users\\Ng??i\\x.vbs", "C:\\Users\\Người\\x.vbs")).toBe(false);
633+
// The forgiven run may never swallow a path separator: a task pointing at a
634+
// different directory must not slip through as "unrepresentable".
635+
expect(taskXmlPathEquals("C:\\Users\\Ng\\evil\\i\\x.vbs", "C:\\Users\\Người\\x.vbs")).toBe(false);
636+
// An entirely ASCII expectation gets no relaxation at all.
637+
expect(taskXmlPathEquals("C:\\Users\\A?c\\x.vbs", "C:\\Users\\Abc\\x.vbs")).toBe(false);
638+
});
639+
585640
// --- #432: Task Scheduler omits schema defaults when exporting ---------------
586641

587642
test("accepts canonicalized scheduler XML with omitted defaults", () => {

0 commit comments

Comments
 (0)